using System.Runtime.InteropServices; namespace SiNan.Common.Extensions { public static class DateTimeExtension { private static readonly DateTime beginTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); /// /// 时间戳转时间 /// /// 时间 /// true:13, false:10 /// [Obsolete] public static DateTime StampToDateTime(this long timeStamp) { DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(beginTime); return timeStamp.ToString().Length == 13 ? dt.AddMilliseconds(timeStamp) : dt.AddSeconds(timeStamp); } /// /// 时间转时间戳 /// /// 时间 /// true:13, false:10 /// public static long DateTimeToStamp(this DateTime time, bool len13 = true) { TimeSpan ts = time.ToUniversalTime() - beginTime; if (len13) return Convert.ToInt64(ts.TotalMilliseconds); else return Convert.ToInt64(ts.TotalSeconds); } /// /// 将秒数转换为时分秒形式 /// /// /// public static string FormatToHHmmss(long second) { if (second < 60) return $"00:00:{(second >= 10 ? $"{second}" : $"0{second}")}"; if (second < 3600) { var minute = second / 60; var s = second % 60; return $"00:{(minute >= 10 ? $"{minute}" : $"0{minute}")}:{(s >= 10 ? $"{s}" : $"0{s}")}"; } else { var hour = second / 3600; var minute = (second - (hour * 3600)) / 60; var s = (second - ((hour * 3600) + minute * 60)) % 60; return $"{(hour >= 10 ? $"{hour}" : $"0{hour}")}:{(minute >= 10 ? $"{minute}" : $"0{minute}")}:{(s >= 10 ? $"{s}" : $"0{s}")}"; } } #region SetLocalTime [DllImport("Kernel32.dll")] private static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime); [StructLayout(LayoutKind.Sequential)] private 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 static void SetSystemTime(DateTime date) { SYSTEMTIME lpTime = new SYSTEMTIME(); lpTime.wYear = Convert.ToUInt16(date.Year); lpTime.wMonth = Convert.ToUInt16(date.Month); lpTime.wDayOfWeek = Convert.ToUInt16(date.DayOfWeek); lpTime.wDay = Convert.ToUInt16(date.Day); DateTime time = date; lpTime.wHour = Convert.ToUInt16(time.Hour); lpTime.wMinute = Convert.ToUInt16(time.Minute); lpTime.wSecond = Convert.ToUInt16(time.Second); lpTime.wMilliseconds = Convert.ToUInt16(time.Millisecond); var r = SetLocalTime(ref lpTime); Console.WriteLine($"修改系统时间 {r}"); } #endregion } }