开发者

Formatting Problem Date with DateTime

I want to display a date with this format :

  • MM/dd/yyyy HH:mm:ss tt

for example :

  • 01/04/2011 03:34:03 PM

but I have a problem with the following code

class Program
{
    static void Main(string[] args)
    {
        DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 0, 0, 0);
        string displayedDate = dt.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
        Console.WriteLine(displayedDate);
        Console.Read();
    }
}

displays :

01/04/2011 12:00:00 AM

instead of

01/04/2011 00:00:00 AM

Anyone knows why ?

Thank 开发者_开发百科you !


Because you've specified a 12-hour clock format instead of a 24-hour format.

The documentation for the DateTime.ToString method gives a full table of format specifiers and what they mean. The choices for hour are as follows:

"h"     The hour, using a 12-hour clock from 1 to 12.
"hh"    The hour, using a 12-hour clock from 01 to 12.
"H"     The hour, using a 24-hour clock from 0 to 23.
"HH"    The hour, using a 24-hour clock from 00 to 23.


So, instead of the hh custom format specifier, you need to use HH. Change this line:

string displayedDate = dt.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

to this:

string displayedDate = dt.ToString("MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);


You have specified that you want a 12-hour format instead of a 24-hour, that's why. You should use HHfor 24-hours. Please see the reference. This should work for you:

string displayedDate = dt.ToString("MM/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);


You'll want to change 'hh' to 'H' in your ToString() call.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜