How can I convert a Unix timestamp to DateTime and vice versa?

前端 未结 19 2480
抹茶落季
抹茶落季 2020-11-21 06:37

There is this example code, but then it starts talking about millisecond / nanosecond problems.

The same question is on MSDN, Seconds since the Unix epoch in C#<

19条回答
  •  后悔当初
    2020-11-21 07:05

    See IdentityModel.EpochTimeExtensions

    public static class EpochTimeExtensions
    {
        /// 
        /// Converts the given date value to epoch time.
        /// 
        public static long ToEpochTime(this DateTime dateTime)
        {
            var date = dateTime.ToUniversalTime();
            var ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
            var ts = ticks / TimeSpan.TicksPerSecond;
            return ts;
        }
    
        /// 
        /// Converts the given date value to epoch time.
        /// 
        public static long ToEpochTime(this DateTimeOffset dateTime)
        {
            var date = dateTime.ToUniversalTime();
            var ticks = date.Ticks - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).Ticks;
            var ts = ticks / TimeSpan.TicksPerSecond;
            return ts;
        }
    
        /// 
        /// Converts the given epoch time to a  with  kind.
        /// 
        public static DateTime ToDateTimeFromEpoch(this long intDate)
        {
            var timeInTicks = intDate * TimeSpan.TicksPerSecond;
            return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks);
        }
    
        /// 
        /// Converts the given epoch time to a UTC .
        /// 
        public static DateTimeOffset ToDateTimeOffsetFromEpoch(this long intDate)
        {
            var timeInTicks = intDate * TimeSpan.TicksPerSecond;
            return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(timeInTicks);
        }
    }
    

提交回复
热议问题