【问题标题】:Converting UK times (both BST and GMT) represented as strings to UTC (in C#)将表示为字符串的英国时间(BST 和 GMT)转​​换为 UTC(在 C# 中)
【发布时间】:2010-12-06 01:45:21
【问题描述】:

我必须使用旧数据库中的一些日期和时间。它们表示为字符串。日期为 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 等的问题?

【问题讨论】:

  • 我需要这个作为通用 TimeInTimeZone->TimeInUTC 方法。

标签: c# .net timezone


【解决方案1】:

尝试在您的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));

【讨论】:

  • 很好,但是您可以为无知者发布一个代码示例吗?这应该是一个规范的资源。
  • 我认为这个例子应该涵盖你需要做的事情。让我知道你是否已经简化了。
  • 我唯一要补充的是,为了获得我提到的实际 DateTime 对象utcTime.UtcDateTime
【解决方案2】:

怎么样:

DateTime.Parse(dateTimeString).ToUniversalTime();

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

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 2018-09-17
    • 2020-09-16
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多