c# - 如何在不丢失 TZinfo 的情况下解析此 DateTime?

标签 c# parsing datetime

我有一堆字符串是从某个数据库转储的 DateTime 值...可能是 MySql。我无法控制结构。

字符串看起来像这样:

2011-05-17 00:00:00 Etc/GMT

我找到了涉及在解析之前替换“Etc/GMT”的解决方案。这闻起来很难闻。

是否有一步解决方案可以在不删除时区信息的情况下将此字符串转换为 DateTime?

最佳答案

DateTime.ParseExact

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

对于时髦的格式,您可以使用 ParseExact。您可能还想使用 DateTimeStyles.AssumeUniversal:

String original = "2011-05-17 00:00:00 Etc/GMT";
DateTime result = DateTime.ParseExact(
    original,
    "yyyy-MM-dd HH:mm:ss 'Etc/GMT'",
    System.Globalization.CultureInfo.InvariantCulture,
    System.Globalization.DateTimeStyles.AssumeUniversal);
Console.WriteLine(result.ToString()); // given my timezone: 5/16/2011 8:00:00 PM
Console.WriteLine(result.ToUniversalTime().ToString()); // 5/17/2011 12:00:00 AM

关于c# - 如何在不丢失 TZinfo 的情况下解析此 DateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18881510/

相关文章:

c# - 如何准确复制您在屏幕上看到的内容?

c# - 在什么情况下我们必须在 linq Query 中使用扩展方法作为 AsEnumerable() 和 ToList()

c# - 使用 C# 的 SQL 格式化程序

c++ - 需要 C++ 解析器

c# - C# 中的日期计算

c# - AdornerLayer.GetAdornerLayer() 为面板中的所有控件返回 NULL

c# - 带有 'failed to load resource : the server responded with a status of 500' 的 Ajax 调用

java - 以编程方式获取 html 文档,模拟网络浏览器

python - 偏移量前滚后加上一个月偏移量后的 Pandas 超出纳秒时间戳

php - 将 Windows 时区转换为 PHP 设置的等效时区