如何将Unix时间戳转换为DateTime,反之亦然?

有这个示例代码,但随后它开始谈论毫秒/纳秒问题。

同样的问题在MSDN上,C#中自Unix纪元以来的秒

这是我到目前为止得到的:

public Double CreatedEpoch{get{DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();TimeSpan span = (this.Created.ToLocalTime() - epoch);return span.TotalSeconds;}set{DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();this.Created = epoch.AddSeconds(value);}}
812586 次浏览

一个Unix滴答是1秒(如果我没记错的话),一个。NET滴答是100纳秒。

如果您遇到纳秒问题,您可能需要尝试使用AddTick(10000000*value)。

这是你需要的:

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp ){// Unix timestamp is seconds past epochDateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime();return dateTime;}

或者,对于Java(这是不同的,因为时间戳是毫秒,而不是秒):

public static DateTime JavaTimeStampToDateTime( double javaTimeStamp ){// Java timestamp is milliseconds past epochDateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);dateTime = dateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();return dateTime;}

我只是通过比较转换到1/1/1970 w/o本地时间调整找到了正确的答案;

DateTime date = new DateTime(2011, 4, 1, 12, 0, 0, 0);DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);TimeSpan span = (date - epoch);double unixTime =span.TotalSeconds;

DateTime到UNIX时间戳:

public static double DateTimeToUnixTimestamp(DateTime dateTime){return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;}

维基百科

UTC不随季节变化而变化,但如果一个时区实行夏令时(夏令时),当地时间或民用时间可能会发生变化。例如,美国东海岸的当地时间在冬季比UTC晚5小时,但在那里实行夏令时则比UTC晚4小时。

这是我的代码:

TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));double unixTime = span.TotalSeconds;

为了补充ScottCher的回答,我最近发现自己陷入了一个恼人的场景,即在输入数据集中任意混合了秒和毫秒的UNIX时间戳。

static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);static readonly double MaxUnixSeconds = (DateTime.MaxValue - UnixEpoch).TotalSeconds;
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp){return unixTimeStamp > MaxUnixSeconds? UnixEpoch.AddMilliseconds(unixTimeStamp): UnixEpoch.AddSeconds(unixTimeStamp);}

我需要将包含UNIX time时间结构(秒,微秒)转换为DateTime而不会丢失精度,并且在这里没有找到答案,所以我想我可以添加我的:

DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);private DateTime UnixTimeToDateTime(Timeval unixTime){return _epochTime.AddTicks(unixTime.Seconds * TimeSpan.TicksPerSecond +unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);}

如果您需要高于毫秒的精度,请小心!

. NET(v4.6)方法(例如从Unix时间毫秒)不提供此精度。

添加秒数寻址毫秒也切断了双精度中的微秒。

这些版本具有高精度:

Unix->DateTime

public static DateTime UnixTimestampToDateTime(double unixTime){DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);long unixTimeStampInTicks = (long) (unixTime * TimeSpan.TicksPerSecond);return new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);}

Unix时间戳

public static double DateTimeToUnixTimestamp(DateTime dateTime){DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);long unixTimeStampInTicks = (dateTime.ToUniversalTime() - unixStart).Ticks;return (double) unixTimeStampInTicks / TimeSpan.TicksPerSecond;}
DateTime unixEpoch = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);DateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);

当然,可以使unixEpoch成为全局静态,因此它只需要在您的项目中出现一次,如果UNIX时间以秒为单位,则可以使用AddSeconds

走另一条路:

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

根据需要截断到Int64和/或使用TotalSeconds

最新版本的. NET(v4.6)增加了对Unix时间转换的内置支持。这包括以秒或毫秒表示的往返Unix时间。

  • Unix时间(以秒为单位)到UTCDateTimeOffset

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
  • DateTimeOffset到Unix时间(秒):

long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
  • Unix时间(毫秒到UTCDateTimeOffset):

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
  • DateTimeOffset到Unix时间(毫秒):

long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();

注意:这些方法与UTCDateTimeOffset相互转换。要获得DateTime表示,只需使用DateTimeOffset.UtcDateTimeDateTimeOffset.LocalDateTime属性:

DateTime dateTime = dateTimeOffset.UtcDateTime;

身份模型。纪元时间扩展

public static class EpochTimeExtensions{/// <summary>/// Converts the given date value to epoch time./// </summary>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;}
/// <summary>/// Converts the given date value to epoch time./// </summary>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;}
/// <summary>/// Converts the given epoch time to a <see cref="DateTime"/> with <see cref="DateTimeKind.Utc"/> kind./// </summary>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);}
/// <summary>/// Converts the given epoch time to a UTC <see cref="DateTimeOffset"/>./// </summary>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);}}

对于. NET 4.6及更高版本:

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);}}

Unix时间转换在. NET Framework 4.6中是新的。

您现在可以更轻松地将日期和时间值转换为. NET Framework类型和Unix时间。这可能是必要的,例如,在JavaScript客户端和. NET服务器之间转换时间值时。以下API已添加到时间戳结构

static DateTimeOffset FromUnixTimeSeconds(long seconds)static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)long DateTimeOffset.ToUnixTimeSeconds()long DateTimeOffset.ToUnixTimeMilliseconds()
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();}}

您可以调用UnixTime. UnixTimeToDateTime(双日期时间))

var dt = DateTime.Now;var unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();

//1510396991

var dt = DateTimeOffset.FromUnixTimeSeconds(1510396991);

//[11.11.2017 10:43:11+00:00]

在. net 4.6中,您可以这样做:

var dateTime = DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime;

写了一个最简单的扩展,为我们工作。如果有人找它…

public static class DateTimeExtensions{public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp){
return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;}}
System.DateTimeOffset.Now.ToUnixTimeSeconds()

您可以使用时间戳日期时间戳

例如,我有一个DateTime对象

var dateTime1 = DateTime.Now;

如果我想将其转换为Unix时间戳,可以实现如下

var unixTimeSeconds = new DateTimeOffset(dateTime1).ToUnixTimeSeconds()

如果您想将unix timeStamp转换为普通DateTime,您可以使用此代码段:

var dateTime2 = DateTimeOffset.FromUnixTimeSeconds(unixTimeSeconds).LocalDateTime;

var dateTime2 = DateTimeOffset.FromUnixTimeSeconds(unixTimeSeconds).UtcDateTime;

欲了解更多信息,请访问此链接:

时间戳方法
日期时间偏移。来自Unix时间秒

Unix纪元现在是DateTime类的一部分。将milis转换为DateTime就像

DateTime.UnixEpoch.AddMilliseconds(millis)

在C#8.0(. NET Core 2.1)中,它是一个简单的单行:

DateTime.UnixEpoch.AddSeconds(unixTimeInSeconds)