C# 时间戳 Timestamp Ticks

时间戳

定义

从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();
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值