转换英国时间(BST和GMT)表示为UTC的字符串(在C#中)

时间:2009-10-12 17:50:27

标签: c# .net timezone

我必须使用遗留数据库中的一些日期和时间。它们表示为字符串。日期是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);

但是,如果日期是英国夏令时期,则会给出错误的值。

我可以在这些日期使用“GMT Daylight Time”,但这需要我知道切换的时间。我确信必须有一种不那么费力的方式。

因为我没有使用具有英国时间设置的机器,所以我不能依赖当地时间。

基本上,我需要这样的东西:

// 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)
{
    ...
}

我已经搜索了帖子,但找不到任何直接解决这个问题的内容。当然这也是EST,EDT等问题吗?

2 个答案:

答案 0 :(得分:6)

尝试在TimeZoneInfo实例上使用GetUtcOffset()方法,该方法需要考虑“调整规则”。

使用它应该与原始示例基本相同,但您将使用该方法而不是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));

答案 1 :(得分:0)

怎么样:

DateTime.Parse(dateTimeString).ToUniversalTime();

假设数据库服务器将其日期时间存储在与应用程序服务器相同的时区中。