c# - 在 C# 中将 12 小时格式转换为 24 小时格式

标签 c# .net datetime hour

如何将 DateTime 格式的 12 小时格式转换为 24 小时格式。

我已经尝试将 DateTime 转换为字符串(24 小时格式)并将其转换回 Datetime 格式,但它不起作用。

最佳答案

使用扩展方法也是个好主意。

public static class MyExtensionClass
{
    public static string ToFormat12h(this DateTime dt)
    {
        return dt.ToString("yyyy/MM/dd, hh:mm:ss tt");
    }

    public static string ToFormat24h(this DateTime dt)
    {
        return dt.ToString("yyyy/MM/dd, HH:mm:ss");
    }
}

然后你可以使用这两种方法如下:

var dtNow = DateTime.Now;

var h12Format = dtNow.ToFormat12h();    // "2016/05/22, 10:28:00 PM"
var h24Format = dtNow.ToFormat24h();    // "2016/05/22, 22:28:00"

关于c# - 在 C# 中将 12 小时格式转换为 24 小时格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37370926/

相关文章:

c# - 为什么这个 linq 查询返回一个 bool 值而不是选择的第一个结果?

c# - 针对频繁重复发生的事件完成 TPL 的高效信号任务

c# - Mono Cecil 将带有方法的类添加到程序集中

javascript - 如何使用 Javascript 生成 PDF?

perl - 如何显示当前日期和时间,包括微秒?

javascript - 如何在javascript中以24小时格式比较2个时间

c# - Windows Phone 8.1 在代码隐藏中手动更改资源文件

c# - SDK 2.3 内的 StorageClient 1.7 库。会被支持吗?

c# - 无法获取 div_images 的内部内容,因为内容不是文字

python - Pandas:如何从另一列设置日期时间的小时数?