您好,登錄后才能下訂單哦!
做工程過程,將做工程過程經常用的內容做個收藏,下面內容內容是關于 C#同步網絡時間和本地時間的內容,希望對各位朋友有較大用途。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Runtime;
public class NetTime
{
public DateTime GetBeijingTime()
{
DateTime dt;
WebRequest wrt = null;
WebResponse wrp = null;
try
{
wrp = wrt.GetResponse();
string html = string.Empty;
using (Stream stream = wrp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
html = sr.ReadToEnd();
}
}
string[] tempArray = html.Split(';');
for (int i = 0; i < tempArray.Length; i++)
{
tempArray[i] = tempArray[i].Replace("rn", "");
}
string year = tempArray[1].Split('=')[1];
string month = tempArray[2].Split('=')[1];
string day = tempArray[3].Split('=')[1];
string hour = tempArray[5].Split('=')[1];
string minite = tempArray[6].Split('=')[1];
string second = tempArray[7].Split('=')[1];
dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second);
}
catch (WebException)
{
return DateTime.Parse("2011-1-1");
}
catch (Exception)
{
return DateTime.Parse("2011-1-1");
}
finally
{
if (wrp != null)
wrp.Close();
if (wrt != null)
wrt.Abort();
}
return dt;
}
}
獲取網絡時間,返回一個DateTime對象,然后傳給設置系統時間的方法,修改系統時間。同步系統時間:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Runtime;
public class UpdateTime
{
[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref SYSTEMTIME time);
[StructLayout(LayoutKind.Sequential)]
private struct 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;
}
public static bool SetDate(DateTime dt)
{
SYSTEMTIME st;
st.year = (short)dt.Year;
st.month = (short)dt.Month;
st.dayOfWeek = (short)dt.DayOfWeek;
st.day = (short)dt.Day;
st.hour = (short)dt.Hour;
st.minute = (short)dt.Minute;
st.second = (short)dt.Second;
st.milliseconds = (short)dt.Millisecond;
bool rt = SetLocalTime(ref st);
return rt;
}
}
兩個方法分別寫在了兩個類里面,只需要在客戶端實例化兩個對象,然后依次調用其方法即可,簡單實用。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。