C# 如何将 Unix 时间戳转换为 DateTime,反之亦然?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/249760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a Unix timestamp to DateTime and vice versa?
提问by Mark Ingram
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#.
同样的问题出现在 MSDN, Seconds since the Unix epoch in C# 上。
This is what I've got so far:
这是我到目前为止所得到的:
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);
}
}
采纳答案by ScottCher
Here's what you need:
这是您需要的:
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;
}
Or, for Java (which is different because the timestamp is in milliseconds, not seconds):
或者,对于 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;
}
回答by Luk
A Unix tick is 1 second (if I remember well), and a .NET tick is 100 nanoseconds.
Unix 滴答是 1 秒(如果我没记错的话),而 .NET 滴答是 100 纳秒。
If you've been encountering problems with nanoseconds, you might want to try using AddTick(10000000 * value).
如果您遇到纳秒问题,您可能想尝试使用 AddTick(10000000 * value)。
回答by n8CodeGuru
I found the right answer just by comparing the conversion to 1/1/1970 w/o the local time adjustment;
仅通过将转换与 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;
回答by Dmitry Fedorkov
DateTime to UNIX timestamp:
日期时间到 UNIX 时间戳:
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}
回答by gl051
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.
UTC 不会随着季节的变化而变化,但如果时区管辖区遵守夏令时(夏令时),则当地时间或民用时间可能会发生变化。例如,美国东海岸的当地时间在冬季比 UTC 晚 5 小时,但在那里遵守夏令时时晚 4 小时。
So this is my code:
所以这是我的代码:
TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0,DateTimeKind.Utc));
double unixTime = span.TotalSeconds;
回答by Chris Thoman
To supplement ScottCher's answer, I recently found myself in the annoying scenario of having both seconds and milliseconds UNIX timestamps arbitrarily mixed together in an input data set. The following code seems to handle this well:
为了补充 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);
}
回答by i3arnon
I needed to convert a timeval struct(seconds, microseconds) containing UNIX time
to DateTime
without losing precision and haven't found an answer here so I thought I just might add mine:
我需要在不丢失精度的情况下转换包含to的timeval 结构(秒,微秒)并且在这里没有找到答案,所以我想我可能会添加我的: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);
}
回答by Felix Keil
Be careful, if you need precision higher than milliseconds!
小心,如果您需要高于毫秒的精度!
.NET (v4.6) methods (e.g. FromUnixTimeMilliseconds) don't provide this precision.
.NET (v4.6) 方法(例如FromUnixTimeMilliseconds)不提供这种精度。
AddSecondsand AddMillisecondsalso cut off the microseconds in the double.
AddSeconds和AddMilliseconds也截断了 double 中的微秒。
These versions have high precision:
这些版本具有高精度:
Unix -> DateTime
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);
}
DateTime -> Unix
日期时间 -> 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;
}
回答by Hot Licks
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.
当然可以做unixEpoch
一个全局静态的,所以只需要在你的项目中出现一次,AddSeconds
如果UNIX时间以秒为单位就可以使用。
To go the other way:
走另一条路:
double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;
Truncate to Int64 and/or use TotalSeconds
as needed.
TotalSeconds
根据需要截断为 Int64 和/或使用。
回答by i3arnon
The latest version of .NET (v4.6)has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.
在.NET(V4.6)的最新版本,增加了内置的Unix时间转换的支持。这包括以秒或毫秒表示的往返 Unix 时间。
- Unix time in seconds to UTC
DateTimeOffset
:
- Unix 时间(以秒为单位)到 UTC
DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
DateTimeOffset
to Unix time in seconds:
DateTimeOffset
以秒为单位的 Unix 时间:
long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
- Unix time in milliseconds to UTC
DateTimeOffset
:
- Unix 时间(以毫秒为单位)到 UTC
DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
DateTimeOffset
to Unix time in milliseconds:
DateTimeOffset
到 Unix 时间(以毫秒为单位):
long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
Note: These methods convert to and from a UTC DateTimeOffset
. To get a DateTime
representation simply use the DateTimeOffset.UtcDateTime
or DateTimeOffset.LocalDateTime
properties:
注意:这些方法与 UTC 相互转换DateTimeOffset
。要获得DateTime
表示,只需使用DateTimeOffset.UtcDateTime
orDateTimeOffset.LocalDateTime
属性:
DateTime dateTime = dateTimeOffset.UtcDateTime;