[英]Create DateTime in specific time zone then convert to utc
我需要創建一個日期和時間設置為特定時區(西亞標准時間、西歐標准時間等)的 DateTime。
必須保留 DST,因此偏移量已取消,因為對於給定的時區,一年中的一半時間為 +2 小時,另一半為 +3 小時。
然后我想將日期轉換為 UTC。
我嘗試以一種可以稍后添加此時區偏移量的方式來執行此操作。 但是,首先我不喜歡這個解決方案,我擔心一年兩次時間變化我會失去一個小時,其次我得到一個錯誤:
“UTC 日期時間實例的 UTC 偏移量必須為 0。”
var testTime = new DateTime(testDate.Year, testDate.Month, testDate.Day, 4, 0, 0, DateTimeKind.Utc);
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("West Asia Standard Time");
var timezoneTime = TimeZoneInfo.ConvertTimeFromUtc(runTime, timeZoneInfo);
var offset = timeZoneInfo.GetUtcOffset(timezoneTime);
我想得到這種代碼
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("West Asia Standard Time");
var testTime = new DateTime(testDate.Year, testDate.Month, testDate.Day, 4, 0, 0, timeZoneInfo);
var utcTime = testTime.ToUniversalTime();
所以,總而言之,我想要一個方法,在那里我傳遞年、月、日、小時、分鍾和時區,作為回報,我將獲得 UTC 中的 DateTime 在 javascript 中有庫,其中給出了給定的時區作為參數,但我必須在服務器端進行。
您基本上需要TimeZoneInfo.ConvertTimeToUtc方法。
只需確保傳遞的DateTime
的Kind
屬性為Unspecified
,否則該方法對sourceTimeZone
參數有特殊期望並會拋出異常。
例如
var testTime = new DateTime(testDate.Year, testDate.Month, testDate.Day, 4, 0, 0);
var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("West Asia Standard Time");
var utcTime = TimeZoneInfo.ConvertTimeToUtc(testTime, timeZoneInfo);;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.