Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

c# - DateTime.Value.ToString(format) gives me 12 hour clock

An extension of this question, I am pulling a date from a database and displaying it in a grid.

I have the following code:

string date = "";
DateTime? dateSent;    

if (row["DateSent"] != DBNull.Value)
                    dateSent = (DateTime)row["DateSent"];
                else dateSent = null;

date = (dateSent.HasValue ? dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") : null);

When I add a breakpoint at the end of this block of code, I can see that the DateTime? variable "dateSent" has a 24-hour clock timestamp eg 14:50:34. However, when I check the value of the string variable "date" - it has a 12-hour clock format eg 02:50:34.

It is not my intention to convert to a 12 hour clock format. I have two questions:

  1. Why is dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") returning a 12 hour clock timestamp?
  2. How can I avoid this and use the 24-hour clock version?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why is dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") returning a 12 hour clock timestamp?

Because you're asking for it. That's what hh means. HH is 24-hour.

When in doubt, read the documentation on custom date and time format strings.

hh is documented as

The hour, using a 12-hour clock from 01 to 12."

HH is documented as:

The hour, using a 24-hour clock from 00 to 23.

As a further note, this comment suggests a potential conceptual error:

I can see that the DateTime? variable "dateSent" has a 24-hour clock timestamp eg 14:50:34

A DateTime value doesn't have a format. It's just a date and time. Just as an int with a value of sixteen is both "0x10" and "16" depending on how you format it, the same is true for DateTime. There's no format which goes around with the value - the results of just calling ToString() will depend on the culture settings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...