如何在C#中获取unix时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17632584/
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 to get the unix timestamp in C#
提问by bizzehdee
I have had look around stackoverflow, and even looked at some of the suggested questions and none seem to answer, how do you get a unix timestamp in C#?
我已经查看了 stackoverflow,甚至查看了一些建议的问题,但似乎没有人回答,你如何在 C# 中获得 unix 时间戳?
采纳答案by bizzehdee
You get a unix timestamp in C# by using DateTime.UtcNowand subtracting the epoch time of 1970-01-01.
通过使用DateTime.UtcNow和减去 1970-01-01 的纪元时间,您可以在 C# 中获得一个 unix 时间戳。
e.g.
例如
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
DateTime.UtcNowcan be replaced with any DateTimeobject that you would like to get the unix timestamp for.
DateTime.UtcNow可以替换为DateTime您想要获取其 Unix 时间戳的任何对象。
There is also a field, DateTime.UnixEpoch, which is very poorly documentedby MSFT, but may be a substitute for new DateTime(1970, 1, 1)
还有一个字段,DateTime.UnixEpoch,MSFT 对它的记录很差,但可以替代new DateTime(1970, 1, 1)
回答by Matthew James Lewis
This is what I use.
这就是我使用的。
public class TimeStamp
{
public Int32 UnixTimeStampUTC()
{
Int32 unixTimeStamp;
DateTime currentTime = DateTime.Now;
DateTime zuluTime = currentTime.ToUniversalTime();
DateTime unixEpoch = new DateTime(1970, 1, 1);
unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
return unixTimeStamp;
}
}
回答by Bart?omiej Mucha
This is what I use:
这是我使用的:
public long UnixTimeNow()
{
var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (long)timeSpan.TotalSeconds;
}
Keep in mind that this method will return the time as Coordinated Univeral Time (UTC).
请记住,此方法将返回时间为协调世界时 (UTC)。
回答by Brad
Truncating .TotalSecondsis important since it's defined as the value of the current System.TimeSpan structure expressed in whole fractional seconds.
截断.TotalSeconds很重要,因为它被定义为the value of the current System.TimeSpan structure expressed in whole fractional seconds.
And how about an extension for DateTime? The second one is probably more confusing that it's worth until property extensions exist.
以及如何扩展DateTime?第二个可能更令人困惑的是,在属性扩展存在之前它是值得的。
/// <summary>
/// Converts a given DateTime into a Unix timestamp
/// </summary>
/// <param name="value">Any DateTime</param>
/// <returns>The given DateTime in Unix timestamp format</returns>
public static int ToUnixTimestamp(this DateTime value)
{
return (int)Math.Truncate((value.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}
/// <summary>
/// Gets a Unix timestamp representing the current moment
/// </summary>
/// <param name="ignored">Parameter ignored</param>
/// <returns>Now expressed as a Unix timestamp</returns>
public static int UnixTimestamp(this DateTime ignored)
{
return (int)Math.Truncate((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
}
回答by Dave Hindle
You can also use Ticks. I'm coding for Windows Mobile so don't have the full set of methods. TotalSecondsis not available to me.
您也可以使用 Ticks。我正在为 Windows Mobile 编码,所以没有完整的方法集。我无法使用TotalSeconds。
long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);
or
或者
TimeSpan epochTicks = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
TimeSpan unixTicks = new TimeSpan(DateTime.UtcNow.Ticks) - epochTicks;
double unixTime = unixTicks.TotalSeconds;
回答by Kelly Anderson
When you subtract 1970 from the current time, be aware that the timespan will most often have a non zero milliseconds field. If for some reason you are interested in the milliseconds, keep this in mind.
当您从当前时间中减去 1970 时,请注意时间跨度通常会有一个非零毫秒字段。如果出于某种原因您对毫秒感兴趣,请记住这一点。
Here's what I did to get around this issue.
这是我为解决此问题所做的工作。
DateTime now = UtcNow();
// milliseconds Not included.
DateTime nowToTheSecond = new DateTime(now.Year,now.Month,now.Day,now.Hour,now.Minute,now.Second);
TimeSpan span = (date - new DateTime(1970, 1, 1, 0, 0, 0, 0));
Assert.That(span.Milliseconds, Is.EqualTo(0)); // passes.
回答by Bob
As of .NET 4.6, there is DateTimeOffset.ToUnixTimeSeconds().
从 .NET 4.6 开始,有DateTimeOffset.ToUnixTimeSeconds().
This is an instance method, so you are expected to call it on an instance of DateTimeOffset. You can also cast any instance of DateTime, though beware the timezone.
这是一个实例方法,因此您应该在 的实例上调用它DateTimeOffset。您也可以投射 的任何实例DateTime,但要注意时区。
To get the current timestamp:
获取当前时间戳:
DateTimeOffset.UtcNow.ToUnixTimeSeconds()
To get the timestamp from a DateTime:
要从 a 获取时间戳DateTime:
DateTime foo = DateTime.UtcNow;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();
回答by Aslan Kystaubayev
This solution helped in my situation:
这个解决方案对我的情况有所帮助:
public class DateHelper {
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}
}
using helper in code:
在代码中使用助手:
double ret = DateHelper.DateTimeToUnixTimestamp(DateTime.Now)
回答by XDS
I've spliced together the most elegant approaches to this utility method:
我已经将这个实用方法的最优雅的方法拼接在一起:
public static class Ux {
public static decimal ToUnixTimestampSecs(this DateTime date) => ToUnixTimestampTicks(date) / (decimal) TimeSpan.TicksPerSecond;
public static long ToUnixTimestampTicks(this DateTime date) => date.ToUniversalTime().Ticks - UnixEpochTicks;
private static readonly long UnixEpochTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
}
回答by Erkin Eren
The simple code that I am using:
我正在使用的简单代码:
public static long CurrentTimestamp()
{
return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds * 1000);
}
This code is giving unix timestamp, total milliseconds from 1970-01-01to now.
这段代码给出了 Unix 时间戳,从1970-01-01到现在的总毫秒数。

