Welcome 微信登录
编程资源 图片资源库

首页 / 软件开发 / .NET编程技术 / 在.Net2.0下获取世界各时区信息及夏令时信息

在.Net2.0下获取世界各时区信息及夏令时信息2012-01-20 博客园 KenBlove在.Net 3.5下有一个TimeZoneInfo类,可以很方便的转换时区和进行时间转换.但是在.Net 2.0下,只能对当前服务器时区进行处理,十分不方便.特别系统是世界范围使用的,更需要考虑当地时区特别是夏令时的问题,不然时间就会错乱.如何解决这个问题,就要通过自己手动处理了.

其实Windows的时区信息都存放在Windows注册表的"SOFTWAREMicrosoftWindows NTCurrentVersionTime Zones"下.只要读取相关信息出来.就能实现和TimeZoneInfo相同的功能.下边我们就通过一个小demo.读取世界时区信息,计算时区偏移量和夏令时偏移量.并根据用户选择的时区和输入时间,判断该时间是否属于该时区的夏令时范围.

首先,我们需要创建两个Struct来记录相关信息,一个是SytemTime,一个TimeZoneInformation.代码如下:

[StructLayout(LayoutKind.Sequential)]
struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
public void SetInfo(byte[] info)
{
if (info.Length != Marshal.SizeOf(this))
{
throw new ArgumentException("Information size is incorrect", "info");
}
else
{
this.wYear = BitConverter.ToUInt16(info, 0);
this.wMonth = BitConverter.ToUInt16(info, 2);
this.wDayOfWeek = BitConverter.ToUInt16(info, 4);
this.wDay = BitConverter.ToUInt16(info, 6);
this.wHour = BitConverter.ToUInt16(info, 8);
this.wMinute = BitConverter.ToUInt16(info, 10);
this.wSecond = BitConverter.ToUInt16(info, 12);
this.wMilliseconds = BitConverter.ToUInt16(info, 14);
}
}
public override bool Equals(object obj)
{
if (this.GetType() == obj.GetType())
{
try
{
SYSTEMTIME objSt = (SYSTEMTIME)obj;
if (this.wYear != objSt.wYear
|| this.wMonth != objSt.wMonth
|| this.wDayOfWeek != objSt.wDayOfWeek
|| this.wDay != objSt.wDay
|| this.wHour != objSt.wHour
|| this.wMinute != objSt.wMinute
|| this.wSecond != objSt.wSecond
|| this.wMilliseconds != objSt.wMilliseconds)
return false;
else
return true;
}
catch
{
return false;
}
}
else
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}