c#DateTime与unix时间戳互相转换

public class UnixTimeUtil
{
    /// <summary>
    /// 将dateTime格式转换为Unix时间戳
    /// </summary>
    /// <param name="dateTime"></param>
    /// <returns></returns>
    public static int DateTimeToUnixTime(DateTime dateTime)
    {
        return (int)(dateTime - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds;
    }
 
    /// <summary>
    /// 将Unix时间戳转换为dateTime格式
    /// </summary>
    /// <param name="time"></param>
    /// <returns></returns>
    public static DateTime UnixTimeToDateTime(int time)
    {
        if (time < 0)
            throw new ArgumentOutOfRangeException("time is out of range");
 
        return TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).AddSeconds(time);
    }
}

还可以这样子求Unix时间戳:

(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000

 

 

原文链接:https://www.cnblogs.com/yaosj/p/11230626.html

posted @ 2019-12-17 21:27  b̶i̶n̶g̶.̶  阅读(217)  评论(0编辑  收藏  举报