繁体   English   中英

在特定时区创建 DateTime 然后转换为 utc

[英]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方法。

只需确保传递的DateTimeKind属性为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM