c# - 当机器上未安装 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;
解决方案
推荐阅读
- msbuild - Error occurred while restoring NuGet packages: The MSBuildProjectExtensionsPath MSBuild property could not be found for project Setup.wixproj
- reactjs - 在 React 中为某些路由使用布局
- java - I cannot figure out why the code keeps printing a value of one more than what I need
- python - Python网络浏览器在同一选项卡中打开网址
- javascript - React 中的 MSO 条件
- angular - 使用 Angular font-awesome 安装 font awesome pro 版本
- php - 如何从命令行将参数传递给 Laravel Dusk
- javascript - 关于fabricjs的组功能的困惑
- php - 如何使用 xampp 和 php 正确安装和运行 grpc
- python-3.x - 当我尝试读取这个excel文件时,Python为什么只有第一个for循环有效,而第二个循环无效?