c# - DateTime.Value.ToString(format) 给我 12 小时制

标签 c#

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 小时时钟格式。我有两个问题:

  1. 为什么 dateSent.Value.ToString("dd/MM/yyyy hh:mm:ss") 返回 12 小时时钟时间戳?
  2. 如何避免这种情况并使用 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/

相关文章:

c# - 系统参数异常 : Invalid postback or callback argument

c# - WCF + EF 4.1 预加载和序列化问题

c# - Base64 在 SQL 中编码一个 utf8 字符串

c# - 在 getter 中使用 if 表达式

c# - 继承 WPF 按钮并在其中添加额外的文本 block

c# - toString保留小数位

c# - Ajax 函数不显示 JSON 日期列表 (Mvc5)

c# - 将 CookComputing XMLRpcStruct (IEnumerable<Object>) 转换为实际的 C# 类

c# - 转换泛型参数

c# - 输入类型文件,所需属性不起作用