我有一个字符串"2012.12.04T08:35:00",它表示"W. Europe Standard Time"时区的时间。现在,我想将其正确转换为UTC时间的c# DateTime对象。请问如何正确地完成这个操作?
可能重复:
C# Datetimes: Conversion for different time zones
可能重复:
C# Datetimes: Conversion for different time zones
在转换时间区时,使用TimeZoneInfo
来处理 具体 的时区:
TimeZoneInfo westInfo =
TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
DateTime westTime = DateTime.Parse("2012.12.04T08:35:00");
DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(westTime, westInfo);
DateTime.Parse
不对给定值的时区做任何假设,它将其存储为具有 Unspecified
的 DateTimeKind
。TimeZoneInfo.ConvertTimeToUtc
预期一个Unspecified
日期时间,并将其视为在明确指定的时区中,然后将其转换为UTC。TimeZoneInfo.ConvertTimeToUtc
" 函数期望一个未指定时区的日期时间。虽然可能只是我太过挑剔,但我不同意这种说法!文档说明了如果 DateTime 已经是 UTC 时间,则不进行转换,否则将假定相对于转换中使用的时区的本地时间。 - JamesDateTime
,年份为2012年,月份为12月,日期为4日,小时为7点,分钟为35分,秒数为0秒。 - RawlingDateTime convertedDate = DateTime.Parse("2012.12.04T08:35:00");
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
你可能需要将 .
更改为 -
。
然后您应该能够使用此方法获取UTC时间。
convertedDate.ToUniversalTime();
http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx
编辑(来自评论的更正):
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
DateTime convertedTime = TimeZoneInfo.ConvertTimeToUtc(convertedDate, tst);
http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx
ToUniversal
将使用本地时区信息,即机器本身的时区,转换日期时间。 - James
DateTime
没有时区的概念。它们可以指定DateTimeKind
,以便您可以说明日期是本地时间还是 UTC 时间。 - Phil Gan