开发者

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

Is there any way to use the DateTime.ToString开发者_StackOverflow社区() 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."


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));
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜