给大家分享一个静态类,可以很方便地把时间戳转换日期格式输出。
调用方法和效果如下:
using System;
using UnityEngine;
private void Start()
{
DateTime dateTime = TimestampHelper.GetDateTime(1482115779);
Debug.Log(dateTime.Year+"年"+ dateTime.Month+"月"+ dateTime.Day + "日");
DateTime dateTime_2 = TimestampHelper.GetDateTime("1482115779");
Debug.Log(dateTime_2.Hour + ":" + dateTime.Minute + ":" + dateTime.Second);
}
下面展示一些 静态类 TimestampHelper
。
/// <summary>
/// 日期类型转换工具
/// </summary>
public static class TimestampHelper
{
/// <summary>
/// Unix时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">Unix时间戳格式,例如:1482115779, 或long类型</param>
/// <returns>C#格式时间</returns>
public static DateTime GetDateTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">Unix时间戳格式</param>
/// <returns>C#格式时间</returns>
public static DateTime GetDateTime(long timeStamp)
{
DateTime time = new DateTime();
try
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
time = dtStart.Add(toNow);
}
catch
{
time = DateTime.Now.AddDays(-30);
}
return time;
}
/// <summary>
/// DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long ToLong(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (long)(time - startTime).TotalSeconds;
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
}