77

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 :)

2
  • 2
    Where is the am/pm marker being added as it is not in your formatting string e.g. 'tt'? Commented Nov 14, 2011 at 21:33
  • 8
    For some reason what you say the format string produces (11/14/2011 2:24:56 am) is very different from what I would expect the format string you posted (yyyy-MM-dd hh:mm:ss) to produce. Are you sure about this?
    – Oded
    Commented Nov 14, 2011 at 21:36

3 Answers 3

189

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.

1
  • I had to use MomentJS just to do that, this saves hell lot of time :)
    – absqueued
    Commented May 28, 2015 at 12:42
6

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.

1

We have to use the DateTime.Now.ToString("yyyy/MM/dddd HH:mm:ss"). We must use Capital HH for 24 hours format that would avoid discrepancies in accurate presentation of date time.

Must Avoid Mistakes using Date Time in C#