Unix time is the time value used in Unix based operating systems and is often exposed by Unix based APIs. To convert it to, or from, a .NET System.DateTime simply calculate the number of seconds since the Unix Epoch, midnight on the 1st January 1970. I’ve created a little class you can use to do just that. Note that the Unix Epoch is UTC, so you should always convert your local time to UTC before doing the calculation.
public class UnixTime
{
private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long FromDateTime(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
{
return (long)dateTime.Subtract(epoch).TotalSeconds;
}
throw new ArgumentException("Input DateTime must be UTC");
}
public static DateTime ToDateTime(long unixTime)
{
return epoch.AddSeconds(unixTime);
}
public static long Now
{
get
{
return FromDateTime(DateTime.UtcNow);
}
}
}
You can convert from Unix time to a UTC DateTime like this:
var calculatedCurrentTime = UnixTime.ToDateTime(currentUnixTime);
Convert to Unix time from a UTC DateTime like this:
var calculatedUnixTime = UnixTime.FromDateTime(myDateTimeValue);
And get the current time as a UTC time value like this:
Console.Out.WriteLine(UnixTime.Now);
5 comments:
Where were you last week with this Post?! It is funny, because I needed the same thing for an open source project I was doing and wrote code that was very similar.
Omg u don't handle leap seconds!! W00t!
Would it be worth handling DateTimeKind.Local to convert the dateTime to UTC ourselves, and only throw the exception on DateTimeKind.Unspecified?
Mike C,
Yes, that'd be a valuable addition. Thanks.
Will we be able to get another 70+ years by using unsigned 32-bit integers?
Post a Comment