views:

247

answers:

5

By default, the hour in a format string for a DateTime transforms 0 into 12. For example, if you have

DateTime dt = new DateTime(1999, 1, 1, 0, 0, 0);
string s = dt.ToString("h:mm:ss");

the value of s will be "12:0:0", not "0:0:0". Is there a way to get "0:00:00" instead?

+1  A: 
string s = (dt.Hour >= 12 ? dt.Hour - 12 : dt.Hour).ToString() +
    dt.ToString(":mm:ss");

Apparently this was not what you were looking for. The way I read your post, you wanted a 12-hour clock that remapped "12:00" to "0:00" (some international clocks do this), which this produces. There is no format string for this behavior, so you have to create the string yourself.

You can also read more on DateTime format strings here.

lc
This is the only correct answer at the moment, so obviously that's why it was downloaded. The way the question is worded, the accepted answer and the other answers that are visible at the moment do preserve 0 as 0 but they have side effects that change other values that the question did not ask for. They change 1 p.m. from 1 to 13. They change 11 p.m. from 11 to 23. And they keep 12 noon as 12, even though the wording of the question asks for 0 (return 0 instead of 12). Here we go, the only correct answer posted in this thread, and it gets downvoted.
Windows programmer
@Windows programmer - Thanks for that; I'm glad I'm not the only one that read the OP at face value. :)
lc
Where in the question does the OP ask for a 12-hour clock? I'm confused by your comment (and answer), since the OP's DateTime object is initialized to midnight, and the OP asks for a way to prevent the default behavior of "transforms 0 into 12".
Jeff Meatball Yang
@Jeff Meatball Yang: The OP doesn't "ask for a 12-hour clock", but is using one by specifying "**h**:mm:ss". The OP asked how to override the default behavior transforming 0 into 12. Technically yours and the other answers do this as well so I didn't vote them down, but they also have side effects that were *not* asked for in the OP. Yes, I assumed a couple things: that the OP was aware of the format string "H", but more importantly that if the OP wanted a 24-hour clock, they would have specified so. It wasn't worded "how to get a 24-hour clock" it was "how to get 12 to be 0" for a given ex.
lc
+6  A: 

You were close, try using this instead:

string s = dt.ToString("H:mm:ss");
Bryce Kahle
+6  A: 

Try

string s = dt.ToString("H:mm:ss");

Here's the reference page.

Jeff Meatball Yang
Hmm. I thought the OP wanted a 12-hour clock from the looks of it. "By default, the hour...transforms 0 into 12...Is there a way to get "0:00:00" instead?
lc
A: 

Instead of "h:mm:ss", use "H:mm:ss"

julio.g
A: 

You need to use a capital H instead of the lowercase h inside the ToString method.

I.e.

DateTime dt = new DateTime(1999, 1, 1, 0, 0, 0); string s = dt.ToString("H:mm:ss");

Marineio