分享

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

 行走在理想边缘 2020-07-23
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);
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约