Convert UTC DateTime to another Time Zone
我有一个来自数据库记录的UTC DateTime值。 我还有一个用户指定的时区(TimeZoneInfo的一个实例)。 如何将UTC DateTime转换为用户的本地时区? 另外,如何确定用户指定的时区当前是否正在观察夏令时? 我正在使用.NET 3.5。
谢谢,
标记
最好的方法是使用
1 2 3 4 5 6 | // you said you had these already DateTime utc = new DateTime(2014, 6, 4, 12, 34, 0); TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); // it's a simple one-liner DateTime pacific = TimeZoneInfo.ConvertTimeFromUtc(utc, tzi); |
唯一的问题是传入的
如果要将DateTimeOffset转换为另一个DateTimeOffset,可以在TimeZoneInfo中使用专用函数:
1 2 3 4 | DateTimeOffset newTime = TimeZoneInfo.ConvertTime( DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") ); |
看看DateTimeOffset结构:
1 2 3 4 5 6 7 8 9 10 11 12 | // user-specified time zone TimeZoneInfo southPole = TimeZoneInfo.FindSystemTimeZoneById("Antarctica/South Pole Standard Time"); // an UTC DateTime DateTime utcTime = new DateTime(2007, 07, 12, 06, 32, 00, DateTimeKind.Utc); // DateTime with offset DateTimeOffset dateAndOffset = new DateTimeOffset(utcTime, southPole.GetUtcOffset(utcTime)); Console.WriteLine(dateAndOffset); |
对于DST,请参阅TimeZoneInfo.IsDaylightSavingTime方法。
1 | bool isDst = southpole.IsDaylightSavingTime(DateTime.UtcNow); |
Antartica答案仅适用于匹配UTC的时区。 我对这个
1 2 3 4 5 6 7 8 9 10 | static public class DateTimeFunctions { static public DateTimeOffset ConvertUtcTimeToTimeZone(this DateTime dateTime, string toTimeZoneDesc) { if (dateTime.Kind != DateTimeKind.Utc) throw new Exception("dateTime needs to have Kind property set to Utc"); var toUtcOffset = TimeZoneInfo.FindSystemTimeZoneById(toTimeZoneDesc).GetUtcOffset(dateTime); var convertedTime = DateTime.SpecifyKind(dateTime.Add(toUtcOffset), DateTimeKind.Unspecified); return new DateTimeOffset(convertedTime, toUtcOffset); } } |
例:
1 | var currentTimeInPacificTime = DateTime.UtcNow.ConvertUtcTimeToTimeZone("Pacific Standard Time"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // TO get Currrent Time in current Time Zone of your System var dt = DateTime.Now; Console.WriteLine(dt); // Display Time Zone of your System Console.WriteLine(TimeZoneInfo.Local); // Convert Current Date Time to UTC Date Time var utc = TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Local); Console.WriteLine(utc); // Convert UTC Time to Current Time Zone DateTime pacific = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Local); Console.WriteLine(pacific); Console.ReadLine(); |