//时间处理
原理: 拿到当前的unix时间戳(本地windows机或者手机),可以用unix2Day换成年月日,拿到当前的年月日,string,int都可以,方便做对比,就不用考虑自己转换年月日了。
当然,如果仅仅取当前的系统时间,只需要
int a = System.DateTime.Now.Minute;
int b = System.DateTime.Now.Hour;
今后时间处理再也不怕了。
注意服务器时间下发也是unix时间戳
// 获取当前的unix时间戳
public static long nowToTimestamp
{
get { return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000; }
}
//时间戳转换为年月日时分秒
public static string Unix2Day(int timestamp)
{
string strTime = string.Empty;
DateTime dt = new DateTime(1970, 1, 1);
dt = dt.AddSeconds(timestamp).ToLocalTime();
strTime = string.Format("{0}月{1}日{2:D2}:{3:D2}",dt.Month,dt.Day,dt.Hour,dt.Minute);
return strTime;
}
然后: 这个函数可以传入秒数,然后换算成年月日时分秒时间。比如这个物品还多少时间消失等等。配合unix时间戳进行差值处理。非常好用
public static string TimeToChineseString(int timeInSeconds)
{
TimeSpan timeSpan = new TimeSpan(0, 0, 0, timeInSeconds);
StringBuilder text = new StringBuilder();
if (timeSpan.Days > 0)
{
text.Append(timeSpan.Days.ToString("0#"));
text.Append("天");
}
if (timeSpan.Hours > 0)
{
text.Append(timeSpan.Hours.ToString("0#"));
text.Append("时");
}
if (timeSpan.Minutes > 0)
{
text.Append(timeSpan.Minutes.ToString("0#"));
text.Append("分");
}
text.Append(timeSpan.Seconds.ToString("0#"));
text.Append("秒");
return text.ToString();
}