Unix Timestamp in .NET

By Munir

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);
}

4 Responses to “Unix Timestamp in .NET”

  1. UTP Says:

    OKAY!!!

    heheh…I am so out of it …I looked at it like I was never a CS person…whoosh…

  2. ayaz Says:

    It is well known as the ‘Unix epoch’. Look, I found something here:

    http://blogs.msdn.com/brada/archive/2004/03/20/93332.aspx

  3. Phone Number Lookup Says:

    Im glad I found your site. Please post up more pictures!

  4. KittyKat Says:

    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

Leave a Reply