How do you convert Unix epoch time into real time in C#? (Epoch beginning 1/1/1970)
Since .Net 4.6 and above please use DateTimeOffset.Now.ToUnixTimeSeconds()
To not worry about using milliseconds or seconds just do:
public static DateTime _ToDateTime(this long unixEpochTime)
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var date = epoch.AddMilliseconds(unixEpochTime);
if (date.Year > 1972)
return date;
return epoch.AddSeconds(unixEpochTime);
}
If epoch time is in seconds then there is no way you can pass year 1972 adding milliseconds.
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;
}
// convert datetime to unix epoch seconds
public static long ToUnixTime(DateTime date)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return Convert.ToInt64((date.ToUniversalTime() - epoch).TotalSeconds);
}
Should use ToUniversalTime() for the DateTime object.
You actually want to AddMilliseconds(milliseconds), not seconds. Adding seconds will give you an out of range exception.
In case you need to convert a timeval struct (seconds, microseconds) containing UNIX time
to DateTime
without losing precision, this is how:
DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private DateTime UnixTimeToDateTime(Timeval unixTime)
{
return _epochTime.AddTicks(
unixTime.Seconds * TimeSpan.TicksPerSecond +
unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);
}