简体   繁体   中英

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:

     The hour, using a 12-hour clock from 1 to 12.
    The hour, using a 12-hour clock from 01 to 12.
     The hour, using a 24-hour clock from 0 to 23.
    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 HH for 24-hours. Please see the reference . This should work for you:

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

您需要在ToString()调用中将'hh'更改为'H'。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM