this 的扩展问题,我正在从数据库中提取日期并将其显示在网格中。
我有以下代码:
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);
当我在此代码块末尾添加断点时,我可以看到 DateTime?
变量“dateSent”具有 24 小时制时间戳,例如 14:50:34。但是,当我检查 string
变量“date”的值时 - 它具有 12 小时时钟格式,例如 02:50:34。
我无意转换为 12 小时时钟格式。我有两个问题:
- 为什么 dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") 返回 12 小时时钟时间戳?
- 如何避免这种情况并使用 24 小时时钟版本?
最佳答案
Why is dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") returning a 12 hour clock timestamp?
因为你要求它。这就是 hh
的意思。 HH
是 24 小时制。
如有疑问,请阅读 custom date and time format strings 上的文档.
hh
记录为
The hour, using a 12-hour clock from 01 to 12."
HH
记录为:
The hour, using a 24-hour clock from 00 to 23.
作为进一步说明,此评论暗示了一个潜在的概念错误:
I can see that the DateTime? variable "dateSent" has a 24-hour clock timestamp eg 14:50:34
DateTime
值没有格式。这只是一个日期和时间。正如值为 16 的 int
既是“0x10”又是“16”,具体取决于您如何格式化它,DateTime
也是如此。值没有格式 - 仅调用 ToString()
的结果将取决于文化设置。
关于c# - DateTime.Value.ToString(format) 给我 12 小时制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15837609/