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 a 64-bit timestamp has been introduced later.
 

Code

 
The following code converts Unix time to System.DateTime and vice versa:
  1. static class UnixTimeHelper {  
  2.   /// <summary>  
  3.   /// Converts DateTime to Unix time.  
  4.   /// </summary>  
  5.   public static long ToUnixTime(this DateTime time) {  
  6.     var totalSeconds = (long)(time.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;  
  7.   
  8.   
  9.     return totalSeconds;  
  10.   }  
  11.   /// <summary>  
  12.   /// Converts Unix time to DateTime.  
  13.   /// </summary>  
  14.   public static DateTime ToDateTime(long unixTime) {  
  15.     return new DateTime(1970, 1, 1).Add(TimeSpan.FromSeconds(unixTime));  
  16.   }  
  17. }  
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,
  1. using Newtonsoft.Json;  
  2. using Newtonsoft.Json.Converters;  
  3.   
  4. internal class JsonUnixTimeConverter : DateTimeConverterBase {  
  5.   public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {  
  6.     if (reader.TokenType != JsonToken.Integer)  
  7.       throw new Exception("Unexpected token type.");  
  8.   
  9.     var unixTime = (long)reader.Value;  
  10.   
  11.     return UnixTimeHelper.ToDateTime(unixTime);  
  12.   }  
  13.   
  14.   public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {  
  15.     if (false == value is DateTime)  
  16.       throw new Exception("Unexpected object type.");  
  17.   
  18.     var dateTime = (DateTime)value;  
  19.   
  20.     var unixTime = UnixTimeHelper.ToUnixTime(dateTime);  
  21.   
  22.     writer.WriteValue(unixTime);  
  23.   }  
  24. }  
Enjoy!