【发布时间】:2019-01-29 01:41:26
【问题描述】:
注意:为方便起见,PowerShell 用于演示该行为,但问题是System.DateTime .NET 类型与System.DateTimeOffset 类型相比的令人惊讶的行为。
这种行为可能有一个很好的概念性原因,但我没有意识到。 如果有,了解为什么以及如何避免这个陷阱会很有帮助。
以下 PowerShell sn-p 演示了 DateTime 实例通过其 Unix 时间等价物以本地时间表示的往返转换:
# Get midnight 1 Jul 2018 in local time.
$date = Get-Date '2018-07-01'
# Convert to Unix time (seconds since midnight 1 Jan 1970 UTC)
# Note: In PowerShell Core this command could be simplified to: Get-Date -Uformat %s $date
$unixTime = [int] (Get-Date -Uformat %s $date.ToUniversalTime())
# Reconvert the Unix time stamp to a local [datetime] instance.
# Note that even though the input string is a UTC time, the cast creates
# a *local* System.DateTime instance (.Kind equals Local)
$dateFromUnixTime1 = ([datetime] '1970-01-01Z').AddSeconds($unixTime)
# Reconvert the Unix time stamp to a local [datetime] instance via
# a [System.DateTimeOffset] instance:
$dateFromUnixTime2 = ([datetimeoffset ] '1970-01-01Z').AddSeconds($unixTime).LocalDateTime
# Output the results
@"
original: $date
Unix time: $unixTime
reconstructed via [datetime]: $dateFromUnixTime1
reconstructed via [datetimeoffset]: $dateFromUnixTime2
"@
以上产量(在我的美式英语系统上Eastern Timezone):
original: 07/01/2018 00:00:00
Unix time: 1530417600
reconstructed via [datetime]: 06/30/2018 23:00:00
reconstructed via [datetimeoffset]: 07/01/2018 00:00:00
如您所见,通过([datetime] '1970-01-01Z') 实例获得的[datetime] 实例(其.Kind 值为Local,即本地 日期)已关闭1 小时,而基于 [datetimeoffset] 的计算(基于 UTC)按预期工作。
我怀疑这与 DST(夏令时)有关 - 例如,2018-12-01 不会发生这种情况 - 但我不清楚为什么。
【问题讨论】:
标签: .net datetime .net-core datetimeoffset date-math