我目前正在开发一个关于asp.net 1.1的项目。我有一个要求,我需要将时区更改为东部标准时间[美国]。我在.net 4.5中有一段代码似乎有所帮助,但在.net 1.1中不支持。
以下是.net 4.5的代码
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime easternTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);
你能帮我解决这个问题。
答案 0 :(得分:2)
在那些日子里我们不得不手动调整时间,因为我们没有帮助者TimeZoneInfo类。
Header part will be Vanished
此示例中的问题是在夏令时期间eastTimeOffset为-4,并且框架中没有好方法来确定要使用的当前偏移量。 通过引入TimeZoneInfo类,在.NET的更高版本中解决了这个问题。
所以,如果你想以更好的方式做事,你应该考虑更新应用程序以使用更新的支持.NET版本
答案 1 :(得分:0)
Really you should upgrade. You only need .NET 3.5 to use TimeZoneInfo
. If you can at least get to .NET 2.0, then you can try TZ4NET. But if you're on 1.1, you have to use code such as the following:
public static DateTime GetCurrentEasternTime()
{
// The current rule for US Eastern Time is:
// -5 => -4: 2nd Sunday in March (2:00 AM Local Time, 7:00 AM UTC)
// -4 => -5: 1st Sunday in November (2:00 AM Local Time, 6:00 AM UTC)
DateTime utcNow = DateTime.UtcNow;
DateTime springTransitionUtc = new DateTime(utcNow.Year, 3, 8, 7, 0, 0);
while (springTransitionUtc.DayOfWeek != DayOfWeek.Sunday)
springTransitionUtc = springTransitionUtc.AddDays(1);
DateTime fallTransitionUtc = new DateTime(utcNow.Year, 11, 1, 6, 0, 0);
while (fallTransitionUtc.DayOfWeek != DayOfWeek.Sunday)
fallTransitionUtc = fallTransitionUtc.AddDays(1);
bool isDst = utcNow >= springTransitionUtc && utcNow < fallTransitionUtc;
int offset = isDst ? -4 : -5;
DateTime easternNow = utcNow.AddHours(offset);
return easternNow;
}