How can I convert a Unix timestamp to DateTime and vice versa?

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#.

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

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):

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

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.

  • Unix time in seconds to DateTimeOffset :
  • DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
    
  • DateTimeOffset to Unix time in seconds:
  • long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
    
  • Unix time in milliseconds to DateTimeOffset :
  • DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
    
  • DateTimeOffset to Unix time in milliseconds:
  • long unixTimeStampInMilliseconds= dateTimeOffset.ToUnixTimeMilliseconds();
    

    Note: These methods convert to and from DateTimeOffset . To get a DateTime representation simply use the DateTimeOffset.DateTime property:

    DateTime dateTime = dateTimeOffset.UtcDateTime;
    

    DateTime到UNIX时间戳:

    public static double DateTimeToUnixTimestamp(DateTime dateTime)
    {
        return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
               new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
    }
    
    链接地址: http://www.djcxy.com/p/25194.html

    上一篇: 将unix时间戳字符串转换为可读的日期

    下一篇: 我如何将Unix时间戳转换为DateTime,反之亦然?