在 C# 中,如何在 DateTime 表示的时间始终将 DateTime 值视为 Europe/London 的本地值,并将其转换为 UTC?
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?
我在我不维护的 SQL 服务器数据库中使用 DateTime 值,我想在我的代码中使用它们作为 UTC。
为了帮助理解问题,我使用的值表示在我们的 CRM 系统中发生操作的时间。
当我从 SQL 服务器检索值时,它们没有时区指示,但我知道它们始终代表 Europe/London - 要么是冬天的 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 值始终应用于 Europe/London 它们代表的时间?
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);
我在我不维护的 SQL 服务器数据库中使用 DateTime 值,我想在我的代码中使用它们作为 UTC。
为了帮助理解问题,我使用的值表示在我们的 CRM 系统中发生操作的时间。
当我从 SQL 服务器检索值时,它们没有时区指示,但我知道它们始终代表 Europe/London - 要么是冬天的 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 值始终应用于 Europe/London 它们代表的时间?
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);