ILoggable

A place to keep my thoughts on programming

March 8, 2008 .net , , ,

Epoch DateTime conversion Extension Methods

Interop with unix often requires dealing with Epoch or Unix time, or the number of seconds since January 1st, 1970 UTC. And if you throw java in the mix, then epoch becomes milliseconds, since they define System.currentTimeMillis() as the number milliseconds since the Epoch. Anyway, i figured, this was the perfect use of Extension methods. Well, almost… There’s still the issue that getting a DateTime object from seconds requires a static method added to DateTime, which extension methods do not currently support. This means that instead of

DateTime utcDateTime = DateTime.FromEpochSeconds(seconds)

we have to be content with

DateTime utcDateTime = DateTimeEx.FromEpochSeconds(seconds)

Now i also added extensions on long and int but, really, that falls into the realm of stupid extension method tricks. I left them in there, only because they are part of DateTimeEx, therefore will only be available if the appropriate namespace is included and so is at least tangentially relevant in the current scope. Well, that’s my rationalization, at least. With this extra extension method you now can do

DateTime utcDateTime = 1205003848.DateTimeFromEpochSeconds();

The one thing to be aware of with all these helpers is that it always deals with UTC time, i.e. the DateTime that you convert to epoch time needs to have a DateTimeKind that is not Unspecified. Conversely, the DateTime you get back is UTC and if you want to deal with it with localtime, you need to call ToLocalTime() on it first.

Anyway, here’s the class:

using System;

namespace Droog.DateTime
{
  public static class DateTimeEx
  {
    public static DateTime FromEpochMilliseconds(long milliseconds)
    {
      return new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Utc).AddMilliseconds(milliseconds);
    }

    public static DateTime FromEpochSeconds(int seconds)
    {
      return FromEpochMilliseconds((long)seconds * 1000);
    }

    public static DateTime DateTimeFromEpochMilliSeconds(this long milliseconds)
    {
      return FromEpochMilliseconds(milliseconds);
    }

    public static DateTime DateTimeFromEpochSeconds(this int seconds)
    {
      return FromEpochSeconds(seconds);
    }

    public static int ToEpochSeconds(this DateTime dt)
    {
      return (int)(ToEpochMilliseconds(dt)/1000);
    }

    public static long ToEpochMilliseconds(this DateTime dt)
    {
      return (long)(dt.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds;
    }
  }
}

Leave a comment