
老规矩,先介绍一下 Unity 的科普小知识:



时间戳 一般是指格林威治时间1970年1月1日0时0分0秒起至现在的总毫秒数。
1970年01月01日00时00分00秒的来历:UNIX系统认为1970年1月1日0点是时间纪元,所以我们常说的UNIX时间戳是以1970年1月1日0点为计时起点时间的。
时间戳在有的地方是以秒数计算的,本文时间戳转换全部以毫秒数计算,防止搞混即可。
//方法一
DateTime now = DateTime.Now;
Debug.Log("当前北京时间:" + now);
//方法二
DateTime utcNow = DateTime.UtcNow;
Debug.Log("当前国际时间:" + utcNow);
//方法一
long now1 = DateTime.UtcNow.Ticks;
Debug.Log("当前时间戳:" + now1);
//方法二
long now2 = DateTime.Now.ToUniversalTime().Ticks;
Debug.Log("当前时间戳:" + now2);
//方法一
TimeSpan st = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0);
Debug.Log("日期转为时间戳:"+Convert.ToInt64(st.TotalMilliseconds));
//方法二
double timeStamp = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000);
Debug.Log("日期转为时间戳:" + timeStamp);
//方法一
DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local);
DateTime dt = startTime.AddMilliseconds(st);//st为传入的时间戳
Debug.Log("时间戳转时间:" + dt);
//方法二
DateTime startTime1 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime dt1 = startTime1.AddMilliseconds(st);//st为传入的时间戳
Debug.Log("时间戳转时间:" + dt);
/// <summary>
/// 将秒数时间戳转换为多久之前。传入时间戳t(t= 当前时间戳() - 指定时间的时间戳 )
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public string GetTimeLongAgo(double t)
{
string str = "";
double num;
if (t < 60)
{
str = string.Format("{0}秒前", t);
}
else if (t >= 60 && t < 3600)
{
num = Math.Floor(t / 60);
str = string.Format("{0}分钟前", num);
}
else if (t >= 3600 && t < 86400)
{
num = Math.Floor(t / 3600);
str = string.Format("{0}小时前", num);
}
else if (t > 86400 && t < 2592000)
{
num = Math.Floor(t / 86400);
str = string.Format("{0}天前", num);
}
else if (t > 2592000 && t < 31104000)
{
num = Math.Floor(t / 2592000);
str = string.Format("{0}月前", num);
}
else
{
num = Math.Floor(t / 31104000);
str = string.Format("{0}年前", num);
}
return str;
} Debug.Log(GetTimeLongAgo(601));