时间戳(Unix时间)

时间:2021-11-06 02:38:03

 

/// <summary>
    /// 时间戳与DateTime互转
    /// </summary>
    public class UnixOfTimeHelper
    {
        /// <summary>
        /// 时间转unix时间戳
        /// </summary>
        /// <param name="date">北京时间1970-01-01 08:00:00</param>
        /// <returns></returns>
        public static double ConvertToUnixOfTime(DateTime date)
        {
            DateTime origin = new DateTime(1970, 1, 1, 8, 0, 0);
            TimeSpan diff = date - origin;
            return Math.Floor(diff.TotalSeconds);
        }

        /// <summary>
        /// unix时间戳转时间
        /// </summary>
        /// <param name="timeStamp">时间戳</param>
        /// <returns></returns>
        public static string StampToDateTime(string timeStamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime result = dateTimeStart.Add(toNow);

            return result.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }