TimeZone.ToLocalTime(DateTime) 方法

定義

傳回對應到指定之日期與時間值的本地時間。

public:
 virtual DateTime ToLocalTime(DateTime time);
public virtual DateTime ToLocalTime (DateTime time);
abstract member ToLocalTime : DateTime -> DateTime
override this.ToLocalTime : DateTime -> DateTime
Public Overridable Function ToLocalTime (time As DateTime) As DateTime

參數

time
DateTime

Coordinated Universal Time (UTC) 時間。

傳回

DateTime 物件,其值為對應至 time 的本地時間。

備註

下表顯示 參數與 DateTime 這個方法所傳回值之間的 time 關聯性。

time 參數 行為 傳回值
國際標準時間 (UTC) 時間 (DateTimeKind.Utc) 。 將時間從 UTC 轉換為當地時間。 DateTime 物件,其值為對應至 time 的本地時間。
當地時間 (DateTimeKind.Local) 。 不需要轉換。 參數所表示的 time 相同 DateTime 值。
未指定的時間 (DateTimeKind.Unspecified) 。 假設時間是 UTC,並將它從 UTC 轉換為當地時間。 DateTime 物件,其值為對應至 time 的本地時間。

如果當地時區觀察到日光節約時間, ToLocalTime 請在執行轉換時套用目前的調整規則 time

注意

方法 ToLocalTime 只會辨識當地時區目前的日光節約時間調整規則。 因此,保證只會在最新調整規則生效的期間,正確傳回對應至特定 UTC 時間的當地時間。 如果 time 是受限於先前調整規則的歷史日期和時間值,它可能會傳回不正確的結果。

方法 ToLocalTime 會對應至 TimeZoneInfo.ConvertTimeFromUtc 方法,其 destinationTimeZone 參數設定為 TimeZoneInfo.Local 。 盡可能使用 TimeZoneInfo.ConvertTimeFromUtc 方法。

給繼承者的注意事項

雖然並非必要,但在大部分情況下,在 .NET Framework 2.0 版下執行的衍生類別應該覆寫此方法的預設實作。 在 .NET Framework 1.0 和 1.1 版中 ToLocalTime ,方法會呼叫 GetUtcOffset(DateTime) 方法,並在傳回當地時間時調整日光節約時間。 不過,從 .NET Framework 2.0 開始,預設實作的行為取決於 Kind 參數的 time 屬性。 如果其值為 Local ,則這個方法會 time 傳回未變更。 如果其值為 UtcUnspecified ,則這個方法假設 time 為 UTC,並將它轉換成本機系統時間,而不呼叫 GetUtcOffset(DateTime) 方法。

下列程式碼提供方法預設實作的 ToLocalTime 簡單覆寫。 在此程式碼中 internalTimeZone ,變數代表 類別的私人 TimeZone 實例:

public override DateTime ToLocalTime(DateTime time)
{
   if (time.Kind == DateTimeKind.Local)
   {
      return time;
   }
   else if (time.Kind == DateTimeKind.Utc)
   {
      DateTime returnTime = new DateTime(time.Ticks, DateTimeKind.Local);
      returnTime += this.GetUtcOffset(returnTime);
      if (internalTimeZone.IsDaylightSavingTime(returnTime))
         returnTime -= new TimeSpan(1, 0, 0);
      return returnTime;
   }      
   else
   {
      throw new ArgumentException("The source time zone cannot be determined.");
   }      
}
Public Overrides Function ToLocalTime(time As Date) As Date
   If time.Kind = DateTimeKind.Local Then
      Return time
   ElseIf time.Kind = DateTimeKind.Utc Then
      Dim returnTime As New Date(time.Ticks, DateTimeKind.Local)
      returnTime += me.GetUtcOffset(returnTime)
      if internalTimeZone.IsDaylightSavingTime(returnTime) Then
         returnTime -= New TimeSpan(1, 0, 0)
      End If
      Return returnTime      
   Else
      Throw New ArgumentException("The source time zone cannot be determined.")
   End If      
End Function

適用於

另請參閱