.netasp.netdatetime

DateTime.ToString() display meridiem as "A.M." or "P.M."


Is there any way to use the DateTime.ToString() method to display the meridiem of the time portion as "A.M." instead of "AM"? I tried using the mask "t.t." but this just outputs "A.A."


Solution

  • You can redefine the AMDesignator and PMDesignator properties of CultureInfo.DateTimeFormat, and then specify the culture as a format provider:

    using System;
    using System.Globalization;
    
    class Program {
        public static void Main() {
            CultureInfo c = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            c.DateTimeFormat.AMDesignator = "A.M.";
            c.DateTimeFormat.PMDesignator = "P.M.";
            Console.WriteLine(DateTime.Now.ToString("tt",c));
        }
    }