簡體   English   中英

使用正確的偏移量將UTC DateTime轉換為EST DateTime

[英]Converting UTC DateTime to EST DateTime with correct offset

我的應用程序以UTC獲取DateTime對象,並需要以EST格式將其輸出為字符串。 我已經嘗試了以下代碼,但是當我得到輸出時,偏移量仍顯示為+00:00而不是-05:00

static void Main(string[] args)
    {
        var currentDate = DateTime.Now.ToUniversalTime();
        var convertedTime = ConvertUtcToEasternStandard(currentDate);

        Console.WriteLine(currentDate.ToString("yyyy-MM-ddTHH:mm:sszzz"));
        Console.WriteLine(convertedTime.ToString("yyyy-MM-ddTHH:mm:sszzz"));
    }

private static DateTime ConvertUtcToEasternStandard(DateTime dateTime)
    {
        var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
        return TimeZoneInfo.ConvertTimeFromUtc(dateTime, easternZone);
    }

輸出:

2016-11-18T06:56:14+00:00
2016-11-18T01:56:14+00:00

因此,時間已正確偏移,但是當我希望偏移量為-05:00時,偏移量保持在+00:00。 知道在使用上述格式字符串輸出時如何獲取具有正確偏移量的DateTime對象嗎?

我基本上是不久前在API中閱讀的,基本上,有了DateTime值,要獲得有用的zzz格式偏移幾乎是不可能的。

使用DateTime值,“ zzz”自定義格式說明符表示本地操作系統時區相對UTC的帶符號偏移,以小時和分鍾為單位。 它不反映實例的DateTime.Kind屬性的值。 因此,不建議將“ zzz”格式說明符與DateTime值一起使用。

使用DateTimeOffset值,此格式說明符以小時和分鍾為單位表示DateTimeOffset值與UTC的偏移量。

偏移量始終以前導符號顯示。 加號(+)表示UTC之前的小時,減號(-)表示UTC之前的小時。 單位偏移量的格式為前導零。


例如,我在美國東部標准時間 ,這是我的結果:

2016-11-18T07:9:38-05:00
2016-11-18T02:9:38-05:00

顯然,UTC時間不應具有-05:00的偏移量。


稍微修改您的代碼,我們有一個解決方案:

void Main()
{
    var currentDate = DateTimeOffset.Now.ToUniversalTime();
    var convertedTime = ConvertUtcToEasternStandard(currentDate);

    var format = "yyyy-MM-ddTHH:m:sszzz";
    Console.WriteLine(currentDate.ToString(format));
    Console.WriteLine(convertedTime.ToString(format));
}

// Define other methods and classes here
private static DateTimeOffset ConvertUtcToEasternStandard(DateTimeOffset dateTime)
{
    var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    return TimeZoneInfo.ConvertTime(dateTime, easternZone);
}

結果:

2016-11-18T07:17:46+00:00
2016-11-18T02:17:46-05:00

這還差不多。

注意:取代了以前的代碼,無知使我受益匪淺,但我沒意識到這是行不通的。 TimeZoneInfo.ConvertTime需要一個DateTimeOffset ,它可以實現我們想要的功能。

如果我們為Pacific Standard Time添加另一種情況:

private static DateTimeOffset ConvertUtcToPacificStandard(DateTimeOffset dateTime)
{
    var pacificZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
    return TimeZoneInfo.ConvertTime(dateTime, pacificZone);
}

我們得到正確的結果:

2016-11-17T23:21:21-08:00

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM