Skip to content

Instantly share code, notes, and snippets.

@txdv
Created July 20, 2011 16:04
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save txdv/1095252 to your computer and use it in GitHub Desktop.
Save txdv/1095252 to your computer and use it in GitHub Desktop.
Epoch class for handling unix times
using System;
namespace Epoch
{
public class Epoch
{
static readonly DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0);
static readonly DateTimeOffset epochDateTimeOffset = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
public static DateTime FromUnix(int secondsSinceepoch)
{
return epochStart.AddSeconds(secondsSinceepoch);
}
public static DateTimeOffset FromUnix(int secondsSinceEpoch, int timeZoneOffsetInMinutes)
{
var utcDateTime = epochDateTimeOffset.AddSeconds(secondsSinceEpoch);
var offset = TimeSpan.FromMinutes(timeZoneOffsetInMinutes);
return new DateTimeOffset(utcDateTime.DateTime.Add(offset), offset);
}
public static int ToUnix(DateTime dateTime)
{
return (int)(dateTime - epochStart).TotalSeconds;
}
public static int Now {
get {
return (int)(DateTime.UtcNow - epochStart).TotalSeconds;
}
}
}
namespace Extensions
{
public static class EpochExtensions
{
public static int ToUnix(this DateTime dateTime)
{
return Epoch.ToUnix(dateTime);
}
public static DateTime FromUnix(this int secondsSinceEpoch)
{
return Epoch.FromUnix(secondsSinceEpoch);
}
public static DateTimeOffset FromUnix(this int secondsSinceEpoch, int timeZoneOffsetInMinutes)
{
return Epoch.FromUnix(secondsSinceEpoch, timeZoneOffsetInMinutes);
}
}
}
}
@ktarbet
Copy link

ktarbet commented Aug 10, 2014

Thanks for posting this! I had a problem with ToUnix with future dates like year 3999. I found some utility here that solved my issue.
https://github.com/OpenDataSpace/System.Data.SQLite/blob/master/System.Data.SQLite/SQLiteConvert.cs

@WalkerWater
Copy link

Thanks man! I copied this code and it made my life simpler!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment