Unix Time to System.DateTime and Vice Versa

Overview

This code demonstrates how to convert between Unix time (Epoch time) and System.DateTime. This code was previously mentioned in my Protrack API post.

Definition

As described by Wikipedia, Unix time (also known as POSIX time or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.

Unix time is represented as a signed 32-bit integer, although an 64-bit timestamp has been introduced later.

Code

The following code converts Unix time to System.DateTime and vice versa:

  static class UnixTimeHelper {
    /// <summary&gt;
    /// Converts DateTime to Unix time.
    /// </summary&gt;
    public static long ToUnixTime(this DateTime time) {
      var totalSeconds = (long)(time.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;


      return totalSeconds;
    }
    /// <summary&gt;
    /// Converts Unix time to DateTime.
    /// </summary&gt;
    public static DateTime ToDateTime(long unixTime) {
      return new DateTime(1970, 1, 1).Add(TimeSpan.FromSeconds(unixTime));
    }
  }

You do not have to worry about leap seconds as System.DateTime does not take leap seconds into account.

JSON DateTime Converter

For whom interested in JSON.NET DateTime/Unix time converter, here’s a sample code:

  using System;
  using Newtonsoft.Json;
  using Newtonsoft.Json.Converters;

  internal class JsonUnixTimeConverter : DateTimeConverterBase {
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
      if (reader.TokenType != JsonToken.Integer)
        throw new Exception("Unexpected token type.");

      var unixTime = (long)reader.Value;

      return UnixTimeHelper.ToDateTime(unixTime);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
      if (false == value is DateTime)
        throw new Exception("Unexpected object type.");

      var dateTime = (DateTime)value;

      var unixTime = UnixTimeHelper.ToUnixTime(dateTime);

      writer.WriteValue(unixTime);
    }
  }

Enjoy!