In one of my current projects, I’m required to calculate Unix Timestamps in my .NET classes. Unix Timestamp is defined as number of second elapsed since January 1, 1970 00:00:00.
.NET also provides a very useful class System.DateTime for Date and Time calculation. Unlike Unix standard, DateTime type in .NET represents date and time values from 12:00:00 midnight, January 1, 0001 A.D. through 11:59:59 P.M., December 31, 9999 A.D. measured in 100-nanoseconds units called Ticks.
Using above facts, here is the simple code for DateTime conversion between these two standards:
long ToUnixTimestamp(System.DateTime dt)
{
DateTime unixRef = new DateTime(1970, 1, 1, 0, 0, 0);
return (dt.Ticks - unixRef.Ticks) / 10000000;
}
DateTime FromUnixTimestamp(long timestamp)
{
DateTime unixRef = new DateTime(1970, 1, 1, 0, 0, 0);
return unixRef.AddSeconds(timestamp);
}
