using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Common { public static class TimeHelper { /// /// 时间转unix时间戳 /// /// /// public static long DateTimeToStamp(DateTime now) { return (now.ToUniversalTime().Ticks - 621355968000000000) / 10000000; } /// /// 获取当前时间戳 /// /// 精度(毫秒)设置 true,则生成13位的时间戳;精度(秒)设置为 false,则生成10位的时间戳;默认为 true /// public static string GetCurrentTimestamp(bool millisecond = true) { return DateTime.Now.ToTimestamp(millisecond); } /// /// 转换指定时间得到对应的时间戳 /// /// /// 精度(毫秒)设置 true,则生成13位的时间戳;精度(秒)设置为 false,则生成10位的时间戳;默认为 true /// 返回对应的时间戳 public static string ToTimestamp(this DateTime dateTime, bool millisecond = true) { return dateTime.ToTimestampLong(millisecond).ToString(); } /// /// 转换指定时间得到对应的时间戳 /// /// /// 精度(毫秒)设置 true,则生成13位的时间戳;精度(秒)设置为 false,则生成10位的时间戳;默认为 true /// 返回对应的时间戳 public static long ToTimestampLong(this DateTime dateTime, bool millisecond = true) { var ts = dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0); return millisecond ? Convert.ToInt64(ts.TotalMilliseconds) : Convert.ToInt64(ts.TotalSeconds); } /// /// 转换指定时间戳到对应的时间(同时增加八个小时) /// /// (10位或13位)时间戳 /// 返回对应的时间 public static DateTime ToDateTime(this long timestamp) { var tz = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0)); if (timestamp.ToString().Length == 13) { return tz.AddMilliseconds(Convert.ToInt64(timestamp)); } else { return tz.AddSeconds(Convert.ToInt64(timestamp)); } } } }