【Code】时间戳转换天时分秒字符串

时间:2022-09-13 21:28:21

这个算是开发的非常常用的功能了,网上都很轻易的搜索到,我也就不再啰嗦原理如何,直接上代码,算是记录一下吧。

using UnityEngine;
using System;

public class Timer
{
private readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

DateTime GetDateTime(int unixTime)
{
return unixEpoch.AddSeconds(unixTime);
}

public string ExpireTime(uint expireTimeStamp, bool isShowFull = false)
{
DateTime lastTime = GetDateTime((int)expireTimeStamp);
DateTime nowTime = DateTime.UtcNow;
string dateDiff = "";
TimeSpan ts1 = new TimeSpan(lastTime.Ticks);
TimeSpan ts2 = new TimeSpan(nowTime.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
if (isShowFull)
{
dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "时" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒";
}
else
{
if (ts.Days > 0)
dateDiff = ts.Days.ToString() + "天";
else if (ts.Hours > 0)
dateDiff = ts.Hours.ToString() + "小时";
else if (ts.Minutes > 0)
dateDiff = ts.Minutes.ToString() + "分钟";
else
dateDiff = ts.Seconds.ToString() + "秒钟";
}
return dateDiff;
}
}

Ricky Yang个人原创,版权所有,转载注明,谢谢。http://blog.csdn.net/yangyy753