我已经环顾stackoverflow,甚至看了一些建议的问题,似乎没有人回答,你如何在c#中获得unix时间戳?


当前回答

系统中DateTimeOffset有一个tounixtimemillisecseconds

你可以为DateTime写类似的方法:

public static long ToUnixTimeSeconds(this DateTime value)
{
    return value.Ticks / 10000000L - 62135596800L;
}

10000000L—将刻度转换为秒

62135596800L -将01.01.01转换为01.01.1978

Utc和泄漏没有问题

其他回答

从。net 4.6开始,就有了datetimeoffset . tounixtimesecseconds。


的实例方法,因此希望在实例上调用它 DateTimeOffset。您还可以强制转换DateTime的任何实例,但要注意 时区。获取当前时间戳:

DateTimeOffset.Now.ToUnixTimeSeconds()

从DateTime中获取时间戳:

DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();

这个解决方案对我的情况很有帮助:

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

在代码中使用helper:

double ret = DateHelper.DateTimeToUnixTimestamp(DateTime.Now)

我正在使用的简单代码:

public static long CurrentTimestamp()
{
   return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds * 1000);
}

这段代码给出了unix时间戳,从1970-01-01到现在的总毫秒数。

我已经拼接了这个实用方法的最优雅的方法:

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

当您从当前时间中减去1970时,请注意,时间跨度通常会有一个非零毫秒字段。如果出于某种原因,您对毫秒感兴趣,请记住这一点。

以下是我解决这个问题的方法。

 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.