C# DateTime与时间戳TimeStamp互转

180it 2024-11-19 AM 85℃ 0条
/// <summary>
/// DateTime转时间戳 
/// </summary>
/// <param name="dt">DateTime</param>
/// <returns>时间戳(秒)</returns>
public static long GetUnixTimeStamp(DateTime dt)
{
    DateTime dtStart = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1, 0, 0, 0), TimeZoneInfo.Local);
    long timeStamp = Convert.ToInt32((dt - dtStart).TotalSeconds);
    return timeStamp;
}
/// <summary>
/// 时间戳转DateTime
/// </summary>
/// <param name="timeStamp">时间戳(秒)</param>
/// <returns>DateTime</returns>
public static DateTime GetDateTimeFromUnixTimeStamp(long timeStamp)
{
    DateTime dtStart = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1, 0, 0, 0), TimeZoneInfo.Local);
    long lTime = ((long)timeStamp * 10000000);
    TimeSpan toNow = new TimeSpan(lTime);
    DateTime targetDt = dtStart.Add(toNow);
    return targetDt;
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

C# DateTime与时间戳TimeStamp互转