首頁 >後端開發 >C++ >如何在不使用本地或UTC的情況下在特定時區(例如PST)中創建DateTime對象?

如何在不使用本地或UTC的情況下在特定時區(例如PST)中創建DateTime對象?

Barbara Streisand
Barbara Streisand原創
2025-01-26 04:16:14201瀏覽

How to Create a DateTime Object in a Specific Time Zone (e.g., PST) in C# Without Using Local or UTC?

在C#中建立特定時區的DateTime物件

在進行涉及時區變更的單元測試時,必須能夠在特定的非本地時區中建立DateTime物件。

問題:

如何在不依賴本地時區或UTC時區的情況下,建立具有特定時區(如PST)的DateTime物件?

答案:

DateTime建構子僅允許使用本地時區、UTC時區或未指定選項。因此,我們可以使用TimeZoneInfo。

解:

為了能夠建立具有特定時區(例如PST)的DateTime對象,請考慮實作自訂結構:

<code class="language-csharp">public struct DateTimeWithZone
{
    private readonly DateTime utcDateTime;
    private readonly TimeZoneInfo timeZone;

    public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
    {
        var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
        utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone);
        this.timeZone = timeZone;
    }

    public DateTime UniversalTime => utcDateTime;

    public TimeZoneInfo TimeZone => timeZone;

    public DateTime LocalTime => TimeZoneInfo.ConvertTime(utcDateTime, timeZone);
}</code>

此結構可讓您建立具有特定時區的DateTime對象,並存取其UTC時間和本地時間。 使用表達式體屬性簡化了程式碼。

以上是如何在不使用本地或UTC的情況下在特定時區(例如PST)中創建DateTime對象?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn