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

前端 未结 19 2464
抹茶落季
抹茶落季 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 06:56
    DateTime unixEpoch = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
    DateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);
    

    Of course, one can make unixEpoch a global static, so it only needs to appear once in your project, and one can use AddSeconds if the UNIX time is in seconds.

    To go the other way:

    double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;
    

    Truncate to Int64 and/or use TotalSeconds as needed.

    0 讨论(0)
  • 2020-11-21 06:57

    Written a simplest extension that works for us. If anyone looks for it...

    public static class DateTimeExtensions
    {
        public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp)
        {
    
            return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 06:57
    public static class UnixTime
        {
            private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    
            public static DateTime UnixTimeToDateTime(double unixTimeStamp)
            {
                return Epoch.AddSeconds(unixTimeStamp).ToUniversalTime();
            }
        }
    

    you can call UnixTime.UnixTimeToDateTime(double datetime))

    0 讨论(0)
  • 2020-11-21 07:01

    From .net 4.6, you can do this:

    var dateTime = DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime;
    
    0 讨论(0)
  • 2020-11-21 07:01

    For .NET 4.6 and later:

    public static class UnixDateTime
    {
        public static DateTimeOffset FromUnixTimeSeconds(long seconds)
        {
            if (seconds < -62135596800L || seconds > 253402300799L)
                throw new ArgumentOutOfRangeException("seconds", seconds, "");
    
            return new DateTimeOffset(seconds * 10000000L + 621355968000000000L, TimeSpan.Zero);
        }
    
        public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
        {
            if (milliseconds < -62135596800000L || milliseconds > 253402300799999L)
                throw new ArgumentOutOfRangeException("milliseconds", milliseconds, "");
    
            return new DateTimeOffset(milliseconds * 10000L + 621355968000000000L, TimeSpan.Zero);
        }
    
        public static long ToUnixTimeSeconds(this DateTimeOffset utcDateTime)
        {
            return utcDateTime.Ticks / 10000000L - 62135596800L;
        }
    
        public static long ToUnixTimeMilliseconds(this DateTimeOffset utcDateTime)
        {
            return utcDateTime.Ticks / 10000L - 62135596800000L;
        }
    
        [Test]
        public void UnixSeconds()
        {
            DateTime utcNow = DateTime.UtcNow;
            DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);
    
            long unixTimestampInSeconds = utcNowOffset.ToUnixTimeSeconds();
    
            DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeSeconds(unixTimestampInSeconds);
    
            Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);
            Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);
            Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);
            Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);
            Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);
            Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);
        }
    
        [Test]
        public void UnixMilliseconds()
        {
            DateTime utcNow = DateTime.UtcNow;
            DateTimeOffset utcNowOffset = new DateTimeOffset(utcNow);
    
            long unixTimestampInMilliseconds = utcNowOffset.ToUnixTimeMilliseconds();
    
            DateTimeOffset utcNowOffsetTest = UnixDateTime.FromUnixTimeMilliseconds(unixTimestampInMilliseconds);
    
            Assert.AreEqual(utcNowOffset.Year, utcNowOffsetTest.Year);
            Assert.AreEqual(utcNowOffset.Month, utcNowOffsetTest.Month);
            Assert.AreEqual(utcNowOffset.Date, utcNowOffsetTest.Date);
            Assert.AreEqual(utcNowOffset.Hour, utcNowOffsetTest.Hour);
            Assert.AreEqual(utcNowOffset.Minute, utcNowOffsetTest.Minute);
            Assert.AreEqual(utcNowOffset.Second, utcNowOffsetTest.Second);
            Assert.AreEqual(utcNowOffset.Millisecond, utcNowOffsetTest.Millisecond);
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:03

    From Wikipedia:

    UTC does not change with a change of seasons, but local time or civil time may change if a time zone jurisdiction observes daylight saving time (summer time). For example, local time on the east coast of the United States is five hours behind UTC during winter, but four hours behind while daylight saving is observed there.

    So this is my code:

    TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));
    double unixTime = span.TotalSeconds;
    
    0 讨论(0)
提交回复
热议问题