views:

174

answers:

2

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."

+9  A: 

Use "t.\\M":

DateTime time = DateTime.Now;
string s = time.ToString("yyyy.MM.dd hh:mm:ss t.\\M.");
Console.WriteLine(s);

Output:

2010.02.02 09:26:14 A.M.

Explanation: t gives the first character of the AM/PM designator (the localized designator can be retrieved in DateTimeFormatInfo.AMDesignator and DateTimeFormatInfo.PMDesignator). The \\M escapes the M so that DateTime.ToString does not interpret it as part of the format string and print the numerical value of the month.

Note that once you do this you are explicitly being culture insensitive. For example, in Japan, the AM/PM designator differs in the second characters, not the first.

Jason
+11  A: 

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));
    }
}
Paolo Tedesco
Nice general solution. This one lends itself better to internationalization.
ladenedge
I realize this is kind of dead, but this issue crept up again for me the other day and I really like this solution. I just had a quick question, if I were to change the AM and PM designators for the current culture (as opposed to creating a copy and using the copy) would that change this setting for all requests until my server is restarted or just for the current request?
Kyle
@Kyle, I cannot test it right now, but I think that you cannot change those properties for the current culture without cloning... give it a try and let me know :)
Paolo Tedesco
@Paolo Well, after testing apparently you can change the properties for the current culture without cloning :) Then you don't need to pass a culture when calling DateTime.ToString(). This setting also appears to only affect the current request.
Kyle