c# 时间戳和DateTime相互转换

时间戳

不含时区的概念
Unix时间戳:是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

DateTime

2021-05-26 23:59:00 北京时间
包含时区的概念,涉及到时间戳和时间的转换,就会有时区的问题。

DateTimeKind.Utc //协调时间
DateTimeKind.Local //本地时间
TimeZone.CurrentTimeZone //获取当前计算机的时区

格式化输出:

t.ToString("yyyy-MM-dd HH:mm:ss fff")

HH: 24小时格式 hh:12小时制

TimeSpan

时间间隔
得到方式一:
用同一时区的DateTime相减,得到TimeSpan
得到方式二:

TimeSpan ts = new TimeSpan(1,8,0);
//1小时8分0秒 还有四个参数,五个参数的方法

格式化输出:

 TimeSpan duration = new TimeSpan(1, 12, 23, 62);
 // Time of Travel: 01.12:24:02
 output = "Time of Travel: " + duration.ToString(@"dd\.hh\:mm\:ss");

时间戳和DateTime相互转换

  //本地时间转换为时间戳
        public static long GetTimeSpan(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
            return (long)(time - startTime).TotalSeconds;
        }

        //时间戳转换为本地时间
        public static DateTime TimeSpanToDateTime(long span)
        {
            DateTime time = DateTime.MinValue;
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
            time = startTime.AddSeconds(span);
            return time;
        }

时间戳和TimeSpan相转换

要不就时间戳转为DateTime,再转成TimeSpan,要不就直接计算:

int day = Mathf.FloorToInt(snap / 86400);
 int hours =  Mathf.FloorToInt(snap / 3600);
 int minutes = Mathf.FloorToInt(snap / 60 % 60);
 int seconds = Mathf.FloorToInt(snap % 60);
 
 string timeS = string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, seconds);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KindSuper_liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值