简体   繁体   English

默认情况下,DateTime.Now 是否总是返回 24 小时格式?

[英]Does DateTime.Now always return a 24 hour format by default?

Currently it is evening and couldn't actually test it with morning hours like 7 in the morning.目前是晚上,实际上无法在早上 7 点左右进行测试。 but a code like this:但是这样的代码:

DateTime dt = DateTime.Now;
string str = dt.ToString("HH:mm");

So my question is can I be sure that it is always returning time in format like "07:35" and not "7:35" ?所以我的问题是我能确定它总是以"07:35"而不是"7:35"格式返回时间?

DateTime.Now returns time without formatting. DateTime.Now返回不带格式的时间。 Format applied in the ToString("HH:mm") method.ToString("HH:mm")方法中应用的格式。 And yes, this format is 24-hour.是的,这种格式是 24 小时制的。

Yes because the documentation says:是的,因为文档说:

The "HH" Custom Format Specifier : The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the hour as a number from 00 through 23; The "HH" Custom Format Specifier定义格式说明符:“HH”自定义格式说明符(加上任意数量的附加“H”说明符)将小时表示为从 00 到 23 的数字; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight.也就是说,小时由从零开始的 24 小时制表示,该时钟计算自午夜以来的小时数。 A single-digit hour is formatted with a leading zero.一位数的小时使用前导零进行格式化。

You could test with你可以测试

DateTime dt = DateTime.Now;
string str = dt.ToString("HH:mm");
Console.WriteLine(str);
DateTime t = new DateTime(2014,3,27,7,5,0);
str = t.ToString("H:mm");
Console.WriteLine(str);

The HH format return always the hour formatted with two digits adding a leading zero when the hour is less than 10, the H format returns the hours formatted with exactly the digits present in the hour part.当小时小于 10 时, HH格式总是返回用两位数字加上前导零格式化的小时, H格式返回用小时部分中存在的数字完全格式化的小时。

You can create an instance of DateTime with desired date and time values using to test various time setting and formats :您可以创建具有所需日期和时间值的 DateTime 实例,用于测试各种时间设置和格式:

var dt = new DateTime(2014, 1, 1, 7, 35, 0);
string str = dt.ToString("HH:mm");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM