我正在尝试使用DaylightSavingTime查找时区和返回时间?
我可以:
但是我在应用规则时遇到问题,这里是代码:
FYI
System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient)
return = 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小时。
答案 0 :(得分:3)
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并确认几个城市。
答案 1 :(得分:3)
我在这里跳了一下,但我不确定你为什么要手动完成这一切。您的整个功能无法替换为:
public static DateTime GetLocalTime(string TimeZoneName)
{
return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName));
}