有这个示例代码,但它开始讨论毫秒/纳秒问题。
同样的问题出在MSDN上, Seconds since the Unix epoch in C# 。
这是我到目前为止所得到的:
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);
}
}
答案 0 :(得分:917)
以下是您的需求:
public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
return dtDateTime;
}
或者,对于Java(由于时间戳以毫秒为单位而不是秒,因此不同):
public static DateTime JavaTimeStampToDateTime( double javaTimeStamp )
{
// Java timestamp is milliseconds past epoch
System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
return dtDateTime;
}
答案 1 :(得分:334)
latest version of .NET (v4.6)增加了对Unix时间转换的内置支持。这包括来自Unix时间和来自Unix或毫秒的时间。
DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
DateTimeOffset
以秒为单位的Unix时间:
long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
DateTimeOffset
到Unix时间,以毫秒为单位:
long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
注意:这些方法与UTC DateTimeOffset
进行转换。要获得DateTime
代表,只需使用DateTimeOffset.UtcDateTime
或DateTimeOffset.LocalDateTime
属性:
DateTime dateTime = dateTimeOffset.UtcDateTime;
答案 2 :(得分:211)
DateTime to UNIX timestamp:
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}
答案 3 :(得分:44)
UTC不随季节的变化而变化,但是当地时间或民间变化 如果时区管辖区遵守夏令时,时间可能会改变 时间(夏令时间)。例如,UTC提前5个小时(即 当天晚些时候在美国东海岸的当地时间 冬季的国家,但夏令时提前4小时 在那里观察。
所以这是我的代码:
TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));
double unixTime = span.TotalSeconds;
答案 4 :(得分:23)
小心,如果你需要精度高于毫秒!
.NET(v4.6)方法(例如 FromUnixTimeMilliseconds )不提供此精度。
AddSeconds 和 AddMilliseconds 也会切断双倍的微秒。
这些版本具有高精度:
Unix - >日期时间强>
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;
}
答案 5 :(得分:13)
请参阅IdentityModel.EpochTimeExtensions
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);
}
}
答案 6 :(得分:10)
为了补充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);
}
答案 7 :(得分:7)
Unix时间转换是.NET Framework 4.6中的新功能。
现在,您可以更轻松地将日期和时间值转换为.NET Framework类型和Unix时间。例如,在JavaScript客户端和.NET服务器之间转换时间值时,这可能是必要的。以下API已添加到Systematically Releasing Objects:
static DateTimeOffset FromUnixTimeSeconds(long seconds)
static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
long DateTimeOffset.ToUnixTimeSeconds()
long DateTimeOffset.ToUnixTimeMilliseconds()
答案 8 :(得分:6)
您可以使用 DateTimeOffset 。
例如。我有DateTime对象
var dateTime1=DateTime.Now;
如果我想将其转换为Unix时间戳,可以实现以下目标
var unixTimeSeconds= new DateTimeOffset(dateTime1).ToUnixTimeSeconds()
如果要将unix timeStamp转换为正常的DateTime,可以使用以下代码段:
var dateTime2 = DateTimeOffset.FromUnixTimeMilliseconds(unixTimeSeconds).LocalDateTime;
或
var dateTime2 = DateTimeOffset.FromUnixTimeMilliseconds(unixTimeSeconds).UtcDateTime;
有关更多信息,请访问此链接:
DateTimeOffset.ToUnixTimeSeconds Method,
DateTimeOffset.FromUnixTimeMilliseconds
答案 9 :(得分:5)
我只是将转换率与当地时间调整的1/1/1970进行比较,找到了正确的答案;
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;
答案 10 :(得分:3)
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
。
答案 11 :(得分:2)
Unix滴答是1秒(如果我记得很清楚),.NET滴答是100纳秒。
如果您遇到纳秒问题,可能需要尝试使用AddTick(10000000 *值)。
答案 12 :(得分:2)
var dt = DateTime.Now;
var unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();
// 1510396991
var dt = DateTimeOffset.FromUnixTimeSeconds(1510396991);
// [11.11.2017 10:43:11 +00:00]
答案 13 :(得分:2)
在.net 4.6中,您可以执行以下操作:
var dateTime = DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime;
答案 14 :(得分:1)
我需要将包含UNIX time
的{{3}}(秒,微秒)转换为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);
}
答案 15 :(得分:1)
写了一个对我们有用的最简单的扩展名。如果有人找...
public static class DateTimeExtensions
{
public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp)
{
return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;
}
}
答案 16 :(得分:1)
System.DateTimeOffset.Now.ToUnixTimeSeconds()
答案 17 :(得分:1)
Unix epoch 现在是 DateTime 类的一部分。将毫秒转换为日期时间就像
一样简单DateTime.UnixEpoch.AddMilliseconds(millis)
答案 18 :(得分:0)
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(double datetime))
答案 19 :(得分:-2)
对于.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);
}
}