I want to display a date with this format :
for example :
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With