C#使用各种时间戳及转换

C#-Unix时间戳及转换

/// <summary>
/// DateTime时间格式转换为13位带毫秒的Unix时间戳
/// </summary>
/// <param name="time">DateTime时间格式</param>
/// <returns>Unix时间戳格式</returns>
public static long ConvertDateTimeLong(DateTime time)
{
    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
    return (long)(time - startTime).TotalMilliseconds;
}

/// <summary>
/// DateTime时间格式转换为10位不带毫秒的Unix时间戳
/// </summary>
/// <param name="time">DateTime时间格式</param>
/// <returns>Unix时间戳格式</returns>
public static long ConvertDateTimeInt(DateTime time)
{
    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
    return (long)(time - startTime).TotalSeconds;
}

/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">Unix时间戳格式</param>
/// <returns>C#格式时间</returns>
public static DateTime GetTime(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);
}
posted @ 2021-10-20 22:23  QAQhong  阅读(2681)  评论(0编辑  收藏  举报