赞
踩
在工作中,经常遇到本地设备与服务器进行时间校验。通常是从服务器获取复凄凄的时间戳,并将时间戳转化为时间,并将该时间设置成本地时间,这样我们就可以保持本地时间和服务器时间的一致性。
class ChangeSYSTime { [DllImport("kernel32.dll")] public static extern bool SetSystemTime(ref SYSTEMTIME st); [DllImport("Kernel32.dll")] public static extern bool SetLocalTime(ref SYSTEMTIME st); [DllImport("Kernel32.dll")] public static extern void GetSystemTime(ref SYSTEMTIME st); [DllImport("Kernel32.dll")] public static extern void GetLocalTime(ref SYSTEMTIME st); public static bool SetLocalTimeByStr(string timestr) { bool flag = false; SYSTEMTIME sysTime = new SYSTEMTIME(); DateTime dt = Convert.ToDateTime(timestr); sysTime.wYear = Convert.ToUInt16(dt.Year); sysTime.wMonth = Convert.ToUInt16(dt.Month); sysTime.wDay = Convert.ToUInt16(dt.Day); sysTime.wHour = Convert.ToUInt16(dt.Hour); sysTime.wMinute = Convert.ToUInt16(dt.Minute); sysTime.wSecond = Convert.ToUInt16(dt.Second); try { flag = SetLocalTime(ref sysTime); } catch(Exception ex) { string e = ex.Message; return false; } return flag; } /// <summary> /// 时间戳转为C#格式时间 /// </summary> /// <param name=”timeStamp”></param> /// <returns></returns> public static DateTime ConvertStringToDateTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } /// <summary> /// 时间戳转为C#格式时间10位 /// </summary> /// <param name="timeStamp">Unix时间戳格式</param> /// <returns>C#格式时间</returns> public static DateTime GetDateTimeFrom1970Ticks(long curSeconds) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); return dtStart.AddSeconds(curSeconds); } } [StructLayout(LayoutKind.Sequential)] public 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; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。