Created
July 20, 2011 16:04
-
-
Save txdv/1095252 to your computer and use it in GitHub Desktop.
Epoch class for handling unix times
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
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
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