2016-11-18 105 views
-1

我的應用程序以UTC獲取DateTime對象,並且需要以EST格式輸出爲字符串。我試着下面的代碼,但是當我得到的輸出偏移仍顯示爲+00:00改爲-05:00使用正確的偏移量將UTC日期時間轉換爲EST日期時間

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對象?

+0

你是在UTC時間,通過任何機會呢? –

+0

是的,英國目前在UTC時間 – Ruddles

+0

這就是你的問題。添加了一個答案。 –

回答

1

我不久前在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 
+0

這很好,讓它在我的應用程序中與這個答案一起工作。謝謝您的幫助 :) – Ruddles

相關問題