How can I convert a Unix timestamp to DateTime and vice versa?
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 UTC
DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
DateTimeOffset
to Unix time in seconds:
long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
- Unix time in milliseconds to UTC
DateTimeOffset
:
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
DateTimeOffset
to Unix time in milliseconds:
long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
Note: These methods convert to and from a UTC DateTimeOffset
. To get a DateTime
representation simply use the DateTimeOffset.UtcDateTime
or DateTimeOffset.LocalDateTime
properties:
DateTime dateTime = dateTimeOffset.UtcDateTime;
Here's what you need:
public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
// Unix timestamp is seconds past epoch
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
return dateTime;
}
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
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
return dateTime;
}
DateTime to UNIX timestamp:
public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
return (TimeZoneInfo.ConvertTimeToUtc(dateTime) -
new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}