Skip to content

Instantly share code, notes, and snippets.

@cdm
Created May 17, 2017 10:50
Show Gist options
  • Save cdm/99004a89433e1882ac6606fcb3c0bfb6 to your computer and use it in GitHub Desktop.
Save cdm/99004a89433e1882ac6606fcb3c0bfb6 to your computer and use it in GitHub Desktop.
public static class DateTimeHelper
{
private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Return the number of seconds since Epoch (1st Jan 1970)
/// </summary>
/// <returns>Seconds since epoch</returns>
public static long SecondsSinceEpoch()
{
TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
int secondsSinceEpoch = (int)t.TotalSeconds;
return secondsSinceEpoch;
}
public static DateTime FromUnixTime(long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(unixTime);
}
public static long ToUnixTime(DateTime dateTime)
{
return (long)(dateTime - unixEpoch).TotalSeconds;
}
public static long ToUnixTimeMilliseconds(DateTime dateTime)
{
return (long)(dateTime - unixEpoch).TotalMilliseconds;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment