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


当前回答

更新的代码从布拉德与一些事情: 你不需要数学。截断,转换为int或long会自动截断值。 在我的版本中,我使用long而不是int(我们将在2038年用完32位有符号整数)。 此外,还添加了时间戳解析。

public static class DateTimeHelper
{
    /// <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 long ToUnixTimestamp(this DateTime value)
    {
        return (long)(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 long UnixTimestamp(this DateTime ignored)
    {
        return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    }

    /// <summary>
    /// Returns a local DateTime based on provided unix timestamp
    /// </summary>
    /// <param name="timestamp">Unix/posix timestamp</param>
    /// <returns>Local datetime</returns>
    public static DateTime ParseUnixTimestamp(long timestamp)
    {
        return (new DateTime(1970, 1, 1)).AddSeconds(timestamp).ToLocalTime();
    }

}

其他回答

在c#中使用DateTime可以获得unix时间戳。UtcNow和减去1970年1月1日的纪元时间。

e.g.

Int32 unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

DateTime。UtcNow可以替换为任何你想获取unix时间戳的DateTime对象。

还有一个字段DateTime。UnixEpoch,它在MSFT的文档中记录得非常少,但可以替代新的DateTime(1970,1,1)

我认为从任何DateTime对象获取unix时间戳会更好。我使用的是。net Core 3.1。

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

从。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 double Convert_DatTime_To_UNIXDATETIME(DateTime dt)
    {
        System.DateTime from_date = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        double unix_time_since = dt.Subtract(from_date).TotalMilliseconds;

        TimeSpan ts_offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

        double offset = ts_offset.TotalMilliseconds;

        return unix_time_since - offset;
    }