【问题标题】:In C#, how can I always treat a DateTime value as being local to Europe/London at the time represented by the DateTime, and convert this to UTC?在 C# 中,如何始终将 DateTime 值视为在 DateTime 表示的时间是欧洲/伦敦的本地值,并将其转换为 UTC?
【发布时间】:2021-07-20 22:57:10
【问题描述】:

我正在使用我不维护的 SQL Server 数据库中的 DateTime 值,并且我想在我的代码中使用它们作为 UTC。

为了帮助理解问题,我使用的值表示在我们的 CRM 系统中发生操作的时间。

当我从 SQL Server 检索值时,它们没有时区指示,但我知道它们始终代表欧洲/伦敦 - 要么是冬季的 UTC,要么是夏季的 UTC+1。

我知道我可以使用 DateTimeKind.Local 来指示 DateTime 值以本地时间表示,但我不明白我如何指定 DateTime 适用于哪个时区。例如,如果我正在使用 DateTime 2021-01-01 12:34:56,我需要确保无论我的代码在何处或何时运行,此日期都被正确解释为 2021-01-01 12:34:56 +00:00。同样,我需要确保无论我的代码在何处或何时运行,我都需要将2021-05-01 12:34:56 解释为2021-05-01 12:34:56 +01:00

如何表明我的 DateTime 值始终适用于它们所代表的时间的欧洲/伦敦?

【问题讨论】:

  • 在没有明确时区指示符的情况下获得本地日期时间值的一个问题是 不明确 值。 IE。相同的当地时间在 DST 过渡日之一出现两次。无法恢复是哪一个。
  • 你不能。在 .NET 中,DateTime 单独是 UTCUndefinedLocal 到执行程序的语言环境。 SQL Server 的datetime 甚至没有,这就是为什么它总是加载为Undefined。您必须使用datetimeoffset 来保留时区偏移量。如果您想要时区本身,则必须明确存储它
  • 为什么不在代码中使用DateTimeOffset,在数据库中使用datetimeoffset?如果时区始终相同,那么您所要求的实际上就是您现在所拥有的:所有DateTime 值都假定为本地值。如果您need to ensure that regardless of where or when my code is running,则需要存储偏移量或时区信息
  • @Damien_The_Unbeliever 这是一个我没有想到的有趣的边缘案例,谢谢。如果我使用“AtLeniently”,Ygalbel 建议的解决方案效果很好。
  • @PanagiotisKanavos 不幸的是,我无法更改数据库架构。我自己的代码正在使用 DateTimeOffset ,这就是这个问题的出现。使用下面建议的 NodaTime,我已经能够将 SQL 日期时间值转换为具有适当偏移量的 DateTimeOffsets :)

标签: c# datetime timezone-offset


【解决方案1】:

Check nodaTime 是一个强大的 C# 日期时间库。 主页中的示例似乎与您的情况有关。

/ Instant represents time from epoch
Instant now = SystemClock.Instance.GetCurrentInstant();

// Convert an instant to a ZonedDateTime
ZonedDateTime nowInIsoUtc = now.InUtc();

// Create a duration
Duration duration = Duration.FromMinutes(3);

// Add it to our ZonedDateTime
ZonedDateTime thenInIsoUtc = nowInIsoUtc + duration;

// Time zone support (multiple providers)
var london = DateTimeZoneProviders.Tzdb["Europe/London"];

// Time zone conversions
var localDate = new LocalDateTime(2012, 3, 27, 0, 45, 00);
var before = london.AtStrictly(localDate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多