c# 获取北京时间更新本地计算机

时间:2025-03-22 10:04:07
     class UpdateDateTime
{
[DllImport("Kernel32.dll")]
private static extern void SetLocalTime([In, Out] SystemTime st); public static void UpdateTime()
{
Uri uri = new Uri("http://www.beijing-time.org/time15.asp");
WebRequest request = WebRequest.Create(uri);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gbk")); string html = reader.ReadToEnd();
reader.Close();
reader.Dispose();
response.Close(); if (html[html.Length-].Equals(';'))
{
html = html.Remove(html.Length - );
} string[] arr = html.Split(';');
SystemTime st = new SystemTime(); foreach (string str in arr)
{
switch (str.Split('=')[].Trim().ToLower())
{
case "nyear":
st.Year = Convert.ToInt16(str.Split('=')[]);
break;
case "nmonth":
st.Month = Convert.ToInt16(str.Split('=')[]);
break;
case "nday":
st.Day = Convert.ToInt16(str.Split('=')[]);
break;
case "nhrs":
st.Hour = Convert.ToInt16(str.Split('=')[]);
break;
case "nmin":
st.Minute = Convert.ToInt16(str.Split('=')[]);
break;
case "nsec":
st.Second = Convert.ToInt16(str.Split('=')[]);
break;
}
}
SetLocalTime(st);
}
} [StructLayout(LayoutKind.Sequential)]
class SystemTime
{
///
///系统时间类
///
public short Year;
public short Month;
public short DayOfWeek;
public short Day;
public short Hour;
public short Minute;
public short Second;
public short Milliseconds;
}