问题描述
我正在使用我不维护的 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-01-01 12:34:56 +01:00
。
如何表明我的 DateTime 值始终适用于它们所代表的时间的欧洲/伦敦?
解决方法
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,45,00);
var before = london.AtStrictly(localDate);