How to use TimeZoneInfo to get local time during Daylight Savings Time?
I'm trying to use DateTimeOffset to convey a specific moment in time across any time zone. I can't figure out how to use TimeZoneInfo to deal with daylight savings time.
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.BaseUtcOffset));
This prints out:
6/2/2010 4:37:19 PM
6/2/2010 3:37:19 PM -06:00
I am in the central time zone, and and we are currently in daylight savings time. I am trying to get the second line to read:
6/2/2010 4:37:19 PM -05:00
BaseUtcOffset apparently doesn't change based on DST.
How can I get the the right time with the proper offset value?
您需要从TimeZoneInfo获取UtcOffset,然后将其传递给ToOffset()方法:
var dt = DateTime.UtcNow;
Console.WriteLine(dt.ToLocalTime());
var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);
Console.WriteLine(utcOffset.ToOffset(tz.GetUtcOffset(utcOffset)));
您还可以使用TimeZoneInfo.ConvertTimeFromUtc,这将允许夏令时:
DateTime utc = DateTime.UtcNow;
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utc, zone);
或者更好,如果你不想硬编码时区标识符:
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id);
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
链接地址: http://www.djcxy.com/p/29388.html