/// <summary> /// 时间戳与DateTime互转 /// </summary> public class TicksTimeConvert { /* * 时间戳10位的是秒,13位的是毫秒 * * 1秒=1000毫秒 * 1毫秒=1000微秒 * 1微秒=1000纳秒,纳秒也叫毫微秒 * * DateTime.Ticks的单位是100纳秒, * 每个计时周期表示一百纳秒,即一千万分之一秒。 * 此属性的值表示自 0001 年 1 月 1 日午夜 12:00:00(表示 DateTime.MinValue)以来经过的以 100 纳秒为间隔的间隔数。 * **/ #region 本地时间 /// <summary> /// 获取当前本地时间 /// </summary> /// <returns></returns> public static DateTime GetNowLocalTime() { return DateTime.Now; //return DateTimeOffset.Now.DateTime; } #endregion #region UTC时间 /// <summary> /// 获取当前UTC时间 /// </summary> /// <returns></returns> public static DateTime GetNowUTCTime() { return DateTime.UtcNow; //return DateTimeOffset.UtcNow.UtcDateTime; } /// <summary> /// 获取当前UTC时间戳 /// </summary> /// <returns>当前UTC时间戳,毫秒,13位</returns> public static long GetNowUTCTicks() { //DateTimeOffset.UtcNow.ToUnixTimeSeconds() //秒,10位 return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();//毫秒,13位 } /// <summary> /// UTC时间转UTC时间戳 /// </summary> /// <param name="UTCTime"> UTC时间</param> /// <returns>UTC时间戳,毫秒,13位</returns> public static long UTCTime2UTCTicks(DateTime UTCTime) { return (new DateTimeOffset(UTCTime)).ToUnixTimeMilliseconds(); } /// <summary> /// UTC时间戳转UTC时间 /// </summary> /// <param name="UTCTicks">UTC时间戳,毫秒,13位</param> /// <returns>UTC时间</returns> public static DateTime UTCTicks2UTCTime(long UTCTicks) { return DateTimeOffset.FromUnixTimeMilliseconds(UTCTicks).UtcDateTime; } #endregion #region 本地和UTC 时间、时间戳互转 /// <summary> /// UTC时间转本地时间 /// </summary> /// <param name="dt">UTC时间</param> /// <returns>本地时间</returns> public static DateTime UTCTime2LocalTime(DateTime UTCTime) { return TimeZone.CurrentTimeZone.ToLocalTime(UTCTime); } /// <summary> /// 本地时间转UTC时间 /// </summary> /// <param name="dt">本地时间</param> /// <returns>UTC时间</returns> public static DateTime LocalTime2UTCTime(DateTime LocalTime) { return LocalTime.ToUniversalTime(); } /// <summary> /// 本地时间转UTC时间戳 /// </summary> /// <param name="LocalTime">本地时间</param> /// <returns>UTC时间戳,毫秒</returns> public static long LocalTime2UTCTicks(DateTime LocalTime) { return UTCTime2UTCTicks(LocalTime2UTCTime(LocalTime)); } /// <summary> /// UTC时间戳转本地时间 /// </summary> /// <param name="UTCTicks">UTC时间戳,毫秒</param> /// <returns>本地时间</returns> public static DateTime UTCTicks2LocalTime(long UTCTicks) { return UTCTime2LocalTime(UTCTicks2UTCTime(UTCTicks)); } #endregion }