时间戳
定义
从1970/01/01 00:00:00开始的累计时间,10位则是累计秒,13位则是累计毫秒;
10位(秒)
精确到秒
例如:2022/11/7 22:07:33 = 1667830053
13位(毫秒)
精确到毫秒
例如:2022/11/7 22:07:33 466 = 1667830053466
Ticks (一千万分之一秒)
例如:
DateTime.Parse("2022/11/7 22:07:33").Ticks
//638034556530000000
2022/11/07 22:07:33 = 638034556530000000(18位)
1970/01/01 00:00:00 = 621355968000000000(18位)
相差为:16678588530000000 Ticks (17位)
10位时间戳:1667858853 秒(10位)
13位时间戳:1667858853000 毫秒(13位)
转换方法
public static class DateTimeExpand
{
public static readonly DateTime ReferenceTime = new DateTime(1970, 1, 1, 0, 0, 0);
/// <summary>
/// 获取时间戳
/// </summary>
/// <param name="dateTime"></param>
/// <param name="isUtc">默认转成UTC时间</param>
/// <param name="isMillisecond">默认使用13位时间戳</param>
/// <returns></returns>
public static long DateTimeToTimestamp(this DateTime dateTime, bool isUtc = true, bool isMillisecond = true)
{
var ticks = dateTime.ToUniversalTime().Ticks - ReferenceTime.Ticks;
if (!isUtc)
{
ticks = dateTime.Ticks - ReferenceTime.Ticks;
}
if (isMillisecond)
{
ticks /= (long)Math.Pow(10, 4); //13位时间戳
}
else
{
ticks /= (long)Math.Pow(10, 7); //10位时间戳
}
return ticks;
}
/// <summary>
/// 时间戳转DateTime
/// </summary>
/// <param name="timestamp">时间戳</param>
/// <param name="isUtc">时间戳是否是UTC时间</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static DateTime TimestampToDateTime(this string timestamp, bool isUtc = true)
{
Regex regex = new Regex(@"(\d){10,13}");
var value = regex.Match(timestamp).Value;
if (string.IsNullOrWhiteSpace(value))
{
throw new Exception($"{timestamp}不是时间戳格式!");
}
while (value.Length < 13)
{
value += "0";
}
var ticks = Convert.ToInt64(value) * (long)Math.Pow(10, 4);
ticks += ReferenceTime.Ticks;
var date = new DateTime(ticks, DateTimeKind.Utc);
if (!isUtc)
{
return new DateTime(ticks, DateTimeKind.Local);
}
return date.ToLocalTime();
}
}