时间戳
不含时区的概念
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);