Date formatting problem with DateTime

I want to show a date with this format:

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

eg:

  • 04/01/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

01/04/2011 00 : 00: 00 am

Does anyone know why?

Thank!

+3
source share
3 answers

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

The documentation for the method DateTime.ToStringgives a complete table of format specifiers and what they mean. The choice of hours is 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.


, hh hh. :

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

:

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

, 12- 24-, . HH 24 . . . :

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

You want to change “hh” to “H” in a call to ToString ().

0
source

Source: https://habr.com/ru/post/1785363/


All Articles