我正在尝试使用DaylightSavingTime查找时区并返回时间?
目前,我可以:
找到时区
获取utc偏移量
根据该时间计算当地时间
确定时区是否使用DaylightSavingTime
获取DaylightSavingTime的规则
确定当前时间是否使用DaylightSavingTime
但是我在应用规则时遇到问题,这是代码:
菲System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient)
返回= 2010/07/10 09:25:45 AM
DateTime localDate = System.DateTime.Now.ToUniversalTime();
// Get the venue time zone info
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
TimeSpan timeDiffUtcClient = tz.BaseUtcOffset;
localDate = System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient);
if (tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(localDate))
{
localDate = localDate.Subtract(tz.GetAdjustmentRules().Single(r => localDate >= r.DateStart && localDate <= r.DateEnd).DaylightDelta);
}
DateTimeOffset utcDate = localDate.ToUniversalTime();
return localDate;
的最终值localDate为{2010/07/10 08:20:40 AM}
应该是{2010/07/10 09:20:40 AM}
由于某种原因,这是1个小时的休假。
最佳答案
好的,我修复了它:
public static DateTime GetLocalTime(string TimeZoneName)
{
DateTime localDate = System.DateTime.Now.ToUniversalTime();
// Get the venue time zone info
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName);
TimeSpan timeDiffUtcClient = tz.BaseUtcOffset;
localDate = System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient);
//DateTimeOffset localDate = new DateTimeOffset(venueTime, tz.BaseUtcOffset);
if (tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(localDate))
{
TimeZoneInfo.AdjustmentRule[] rules = tz.GetAdjustmentRules();
foreach (var adjustmentRule in rules)
{
if (adjustmentRule.DateStart <= localDate && adjustmentRule.DateEnd >= localDate)
{
localDate = localDate.Add(adjustmentRule.DaylightDelta);
}
}
//localDate = localDate.Subtract(tz.GetAdjustmentRules().Single(r => localDate >= r.DateStart && localDate <= r.DateEnd).DaylightDelta);
}
DateTimeOffset utcDate = localDate.ToUniversalTime();
return localDate;
}
要对其进行测试,您可以执行以下操作:
Hashtable list = new Hashtable();
foreach (TimeZoneInfo tzi in TimeZoneInfo.GetSystemTimeZones())
{
string name = tzi.DisplayName;
DateTime localtime = TimeZoneHelper.GetLocalTime(tzi.Id);
list.Add(name, localtime);
}
然后最后在“列表”上进行快速监视,并转到worldtimeserver.com并确认几个城市。
关于c# - 如何使用DaylightSavingTime查找时区和返回时间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3219558/