首页 > 解决方案 > 当机器上未安装 CEST 时区时,从 CEST /CET 日期字符串转换为 UTC 日期字符串

问题描述

我需要解析 CEST/CET 中的一些日期,作为来自外部提供商的字符串,并将它们转换为 UTC。

我当前计算机上的文化是 en-GB,并且我的计算机上安装了 BST 时区,但我没有 CEST。因此,我无法TimeZoneInfo在时区之间进行转换,因为我无法为 CEST 实例化一个。

我如何在 C# 中做到这一点?我在 StackOverflow 上查看了类似的问题,并用谷歌搜索了这个,但我找不到有效的解决方案。

我的代码目前适用于此,但我认为这是一个 hack,仍然:

// dateToParse: "2018-09-04T19:17:37.022363"

var theDate = DateTime.ParseExact(dateToParse,
    @"yyyy-MM-ddTHH\:mm\:ss\.ffffff",
    new CultureInfo("sq-AL"),       // this culture info is in CEST. Tried using CultureInfo.InvariantCulture as well - nothing changed 
    DateTimeStyles.AssumeLocal);    // tried putting here DateTimeStyles.None

// Our local time is in BST. 
// CEST and BST are always one hour apart so parsing date during daylight saving times will (probably) still work. 
// I think. Except for that 1h window when the switch happens...
theDate = theDate.AddHours(-1);  // I was hoping to not need this!
var utcDate = theDate.ToUniversalTime(); 

return utcDate;

所以基本上我正在寻找能够理解日期在 CEST 或 CET 中的东西,具体取决于一年中的时间,而不是我当前的 BST 时间,并且知道如何将其转换为 UTC,并考虑到夏令时等因素.

我不介意使用库 - 我非常非常简要地查看了 NodaTime,但没有找到明显的解决方案(很可能有,但我没有花时间可靠地寻找它)。

非常感谢任何帮助。


在评论的帮助和更多搜索之后,这段代码似乎运行良好:

var theDate = DateTime.ParseExact(dateToParse,
    @"yyyy-MM-ddTHH\:mm\:ss\.ffffff",
    CultureInfo.InvariantCulture,
    DateTimeStyles.None);

var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
var utcDate = TimeZoneInfo.ConvertTimeToUtc(theDate, timeZoneInfo);

return utcDate;

标签: c#

解决方案


推荐阅读