c# - 在 C# 中解析非标准日期字符串

标签 c# iformatprovider datetimeformatinfo

您将如何处理以下需要转换为 DateTime 对象的字符串值?

"2015/01/22 12:08:51 (GMT+09:00)"

希望将此作为公认的 DateTime 模式包括在内。当我遇到其他格式时,我只想实现一种新模式。

最佳答案

这里有一段代码可以成功解析给定的字符串(注意 DateTimeOffset 而不是 DateTime):

var str = "2015/01/22 12:08:51 (GMT+09:00)";

var dt = DateTimeOffset.ParseExact
    (str,
    "yyyy/MM/dd HH:mm:ss (\\G\\M\\TK)",
    System.Globalization.CultureInfo.InvariantCulture
    );
//dt now has +9:00 offset - that's correct only if GMT is provided as UTC.

更多信息请访问 The Difference Between GMT and UTC

关于c# - 在 C# 中解析非标准日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45970679/

相关文章:

c# - ANID 和 ANID2 长度不是 API 所说的 32

c# - 关于 iCustomFormatter 问题的 String.Format 与 int.ToString

C# 创建自定义 NumberFormatInfo 以在货币值为 $0.00 时显示 "Free"

c# - C# 中的 Excel - 2 张纸有问题

c# - 如何使用 MVVM 将 UserControl 从插件传递到我的主窗口?

c# - Azure 应用程序从 machine.config 中获取连接字符串

.net - 我应该总是指定使用哪个 IFormatProvider 吗?

c# - 为什么 DateTimeInfo.MonthNames 返回 13 个成员?

asp.net - 将 ASP.NET 文本框控件 .text 内容转换为日期/时间格式

c# - DateTimeFormatInfo.CurrentInfo 怎么可能为空