Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 840
Florian Avatar asked Feb 10 '26 16:02

Florian


2 Answers

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);
like image 86
Cody Gray Avatar answered Feb 13 '26 14:02

Cody Gray


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);
like image 22
alexn Avatar answered Feb 13 '26 14:02

alexn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!