DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

.NetDatetime

.Net Problem Overview


I'm trying to get the current time via DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")

However, this is spitting out a time 12 hours off of what we want.

For example:

What it spits out: 11/14/2011 2:24:56 am

What we want: 11/14/2011 2:24:56 pm

What noob mistake are we making?

Any help is greatly appreciated :)

.Net Solutions


Solution 1 - .Net

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

Solution 2 - .Net

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser114518View Question on Stackoverflow
Solution 1 - .NetOdedView Answer on Stackoverflow
Solution 2 - .NetCallumView Answer on Stackoverflow