標籤:c#更改系統時間
核心代碼:
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Sockets;using System.Runtime.InteropServices;using System.Text;using System.Threading.Tasks;namespace TestServerTime{ public class ServerInfo { public static string GetHostName() { return Dns.GetHostName(); } public static string GetLocalIP() { string ip = ""; try { string HostName = Dns.GetHostName(); //得到主機名稱 IPHostEntry IpEntry = Dns.GetHostEntry(HostName); for (int i = 0; i < IpEntry.AddressList.Length; i++) { //從IP地址清單中篩選出IPv4類型的IP地址 //AddressFamily.InterNetwork表示此IP為IPv4, //AddressFamily.InterNetworkV6表示此地址為IPv6類型 if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { ip = IpEntry.AddressList[i].ToString(); } } } catch (Exception ex) { throw ex; } return ip; } [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime); [StructLayout(LayoutKind.Sequential)] internal struct SYSTEMTIME { public ushort wYear; public ushort wMonth; public ushort wDayOfWeek; // ignored for the SetLocalTime function public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds; } public static bool SetLocalTimeByStr(string timestr) { bool flag = false; SYSTEMTIME sysTime = new SYSTEMTIME(); string SysTime = timestr.Trim(); //此步驟多餘,為方便程式而用直接用timestr即可 sysTime.wYear = Convert.ToUInt16(SysTime.Substring(0, 4)); sysTime.wMonth = Convert.ToUInt16(SysTime.Substring(4, 2)); sysTime.wDay = Convert.ToUInt16(SysTime.Substring(6, 2)); sysTime.wHour = Convert.ToUInt16(SysTime.Substring(8, 2)); sysTime.wMinute = Convert.ToUInt16(SysTime.Substring(10, 2)); sysTime.wSecond = Convert.ToUInt16(SysTime.Substring(12, 2)); //注意: //結構體的wDayOfWeek屬性一般不用賦值,函數會自動計算,寫了如果不對應反而會出錯 //wMiliseconds屬性預設值為一,可以賦值 try { flag = SetLocalTime(ref sysTime); } //由於不是C#本身的函數,很多異常無法捕獲 //函數執行成功則返回true,函數執行失敗返回false //經常不返回異常,不提示錯誤,但是函數返回false,給尋找錯誤帶來了一定的困難 catch (Exception ex1) { Console.WriteLine("SetLocalTime函數執行異常" + ex1.Message); } return flag; } }}
調用代碼:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace TestServerTime{ class Program { static void Main(string[] args) { string destTime = "2015-11-12 15:09:24"; SetServerTime(destTime); System.Console.WriteLine( DateTime.Now.ToLocalTime()); System.Console.ReadLine(); } public static void SetServerTime(string destTime) { ServerInfo.SetLocalTimeByStr(DateTime.Parse(destTime).ToString("yyyyMMddHHmmss")); } }}
本文出自 “愛工作愛生活” 部落格,請務必保留此出處http://4453154.blog.51cto.com/4443154/1712241
C#更改系統時間