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);
}
October 16, 2008 at 7:53 pm |
OKAY!!!
heheh…I am so out of it …I looked at it like I was never a CS person…whoosh…
October 18, 2008 at 3:59 pm |
It is well known as the ‘Unix epoch’. Look, I found something here:
http://blogs.msdn.com/brada/archive/2004/03/20/93332.aspx
March 29, 2009 at 12:01 am |
Im glad I found your site. Please post up more pictures!
November 10, 2009 at 7:57 am |
public static class DateTimeStuff
{
public static long ToUnixTimestamp(this DateTime dt)
{
DateTime unixRef = new DateTime(1970, 1, 1, 0, 0, 0);
return (dt.Ticks – unixRef.Ticks) / 10000000;
}
public static DateTime FromUnixTimestamp(long timestamp)
{
DateTime unixRef = new DateTime(1970, 1, 1, 0, 0, 0);
return unixRef.AddSeconds(timestamp);
}
}
using the new .net features