How do you convert epoch time in C#?

How do you convert Unix epoch time into real time in C#? (Epoch beginning 1/1/1970)


我认为你的意思是Unix时间,它定义为自1970年1月1日午夜(UTC)以来的秒数。

public static DateTime FromUnixTime(long unixTime)
{
    return epoch.AddSeconds(unixTime);
}
private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

With all credit to LukeH, I've put together some extension methods for easy use:

public static DateTime FromUnixTime(this long unixTime)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.AddSeconds(unixTime);
}

public static long ToUnixTime(this DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date - epoch).TotalSeconds);
}

Note the comment below from CodesInChaos that the above FromUnixTime returns a DateTime with a Kind of Utc , which is fine, but the above ToUnixTime is much more suspect in that doesn't account for what kind of DateTime the given date is. To allow for date 's Kind being either Utc or Local , use ToUniversalTime :

public static long ToUnixTime(this DateTime date)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}

ToUniversalTime will convert a Local (or Unspecified ) DateTime to Utc .

if you dont want to create the epoch DateTime instance when moving from DateTime to epoch you can also do:

public static long ToUnixTime(this DateTime date)
{
    return (date.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}

The latest version of .Net (v4.6) just 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;
    
    链接地址: http://www.djcxy.com/p/18484.html

    上一篇: 使用epoch自动初始化一个日期时间对象

    下一篇: 你如何在C#中转换时代?