【发布时间】:2020-08-06 22:35:11
【问题描述】:
我正在尝试确定将当前夏令时添加到 ZonedDateTime 的正确方法。下面的方法好像可以,只要金额是正数就行,不知道有没有更好的方法?
' Get the current moment in time
Dim now As Instant = SystemClock.Instance.GetCurrentInstant()
' Convert to UTC time
Dim UtcDateTime As ZonedDateTime = now.InUtc
' Get this computer's Local TimeZone
Dim LocalTimeZone As DateTimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault()
' Convert the UTC DateTime to the time in the Local TimeZone
Dim LocalDateTime As ZonedDateTime = UtcDateTime.WithZone(LocalTimeZone)
' The above code is just to set things up. The following code is the question:
' Check if Daylight Savings Time is in force
Dim DstInForce As Boolean = LocalDateTime.IsDaylightSavingTime
' Get the Interval for the Local TimeZone
Dim LocalInterval As ZoneInterval = LocalTimeZone.GetZoneInterval(LocalDateTime.ToInstant)
' If Daylight Savings Time is in force, add the Savings Amount
If DstInForce = True Then
LocalDateTime.PlusSeconds(CLng(LocalInterval.Savings.ToTimeSpan.TotalSeconds))
End If
编辑添加..
这是另一个工作示例:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim NowDateTime As LocalDateTime = New LocalDateTime(2020, 8, 5, 9, 15)
Dim UtcZone As DateTimeZone = DateTimeZoneProviders.Tzdb("UTC")
Dim UtcDateTime As ZonedDateTime = NowDateTime.InZoneLeniently(UtcZone)
TextBox1.AppendText("It is currently " & UtcDateTime.ToString & " in zone " & UtcZone.ToString & vbCrLf)
Dim ThisComputerTimeZone As DateTimeZone = DateTimeZoneProviders.Tzdb("Europe/London")
Dim ThisComputerDateTime As ZonedDateTime = UtcDateTime.WithZone(ThisComputerTimeZone)
' Check if Daylight Savings Time is in force
Dim DstInForce As Boolean = ThisComputerDateTime.IsDaylightSavingTime
Dim ThisComputerInterval As ZoneInterval = ThisComputerTimeZone.GetZoneInterval(ThisComputerDateTime.ToInstant)
If DstInForce = True Then
' If Daylight Savings Time is in force, add the Savings Amount
ThisComputerDateTime.PlusSeconds(CLng(ThisComputerInterval.Savings.ToTimeSpan.TotalSeconds))
End If
TextBox1.AppendText("It is currently " & ThisComputerDateTime.ToString & " in local zone " & ThisComputerTimeZone.ToString & vbCrLf)
TextBox1.AppendText("Daylight Savings Time is '" & DstInForce & "' and has been applied." & vbCrLf)
End Sub
这是它的输出:
It is currently 2020-08-05T09:15:00 UTC (+00) in zone UTC
It is currently 2020-08-05T10:15:00 Europe/London (+01) in local zone Europe/London
Daylight Savings Time is 'True' and has been applied.
如您所见,我需要添加额外的 Savings 金额以将 UTC 时间“09:15”更改为夏令时“10:15”。我想做什么?我正在尝试创建一个 UTC 时间,然后将其更改为我的计算机的本地时间,其中包含正确的 DST 量。这些步骤是更大过程的一部分,为清楚起见已缩写。
【问题讨论】:
-
首先,我真的,真的强烈建议您不要将
ZonedDateTime类型的变量命名为LocalDateTime。当LocalDateTime是另一种类型时,这真的令人困惑。这就像声明一个名称为Integer的String变量。但除此之外,尚不清楚您要达到的目标。ZonedDateTime已经考虑了夏令时。为什么要添加 second 次?你能举一个具体的例子来说明你想要完成的事情吗? -
我已经编辑了我的示例以包含代码的工作示例。由于其他原因,我需要从 UTC 开始,然后将其转换为另一个时区,并考虑 DST。
-
我看到您已删除“已接受的答案” - 如果还有什么问题仍然无法正常工作,请告诉我?
-
我不确定为什么要删除它。是的,现在一切都很好。非常感谢您抽出时间提供帮助。