我必须使用遗留数据库中的一些日期和时间.它们表示为字符串.日期是dd/MM/yy.时间是HH:mm.
我想从数据库中提取它们后立即将这些转换为UTC.我正在研究美国的系统,所以需要一个共同的时间.
我面临的问题是如何将它们转换为UTC DateTime值.我可以进行解析等.我遇到的真正问题涉及时区.
我正在尝试使用以下方法:
DateTime ukTime = // Parse the strings in a DateTime value.
TimeZoneInfo timeZoneInformation = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTimeOffset utcTime = new DateTimeOffset(ukTime, timeZoneInformation.BaseUtcOffset);
Run Code Online (Sandbox Code Playgroud)
但是,如果日期在英国夏令时期间,则会给出不正确的值.
我可以在这些日期使用"GMT日光时间",但这需要我知道切换的时间.我敢肯定必须有一种不那么费力的方式.
因为我没有使用具有英国时间设置的机器,所以我不能依赖当地时间.
基本上,我需要这样的东西:
// Works for both GMT (UTC+0) and BST (UTC+1) regardless of the regional settings of the system it runs on.
DateTime ParseUkTimeAsUtcTime(string date, string time)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我已经搜索了帖子,但找不到任何直接解决这个问题的内容.当然这也是EST,EDT等问题?
尝试GetUtcOffset()在您的TimeZoneInfo实例上使用该方法,该方法需要考虑"调整规则".
使用它应该与原始示例基本相同,但您将使用该方法而不是BaseUtcOffset属性.
DateTime ukTime = // Parse the strings in a DateTime value.
TimeZoneInfo timeZoneInformation = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
DateTimeOffset utcTime = new DateTimeOffset(ukTime, timeZoneInformation.GetUtcOffset(ukTime));
Run Code Online (Sandbox Code Playgroud)