Menü Schließen

Convert .NET DateTime into Unix Time

The Unix calendar starts at 01/01/1970. This post will show you how to convert any DateTime value into a Unix time stamp.

private const string InvalidUnixEpochErrorMessage = "Unix time starts January 1st, 1970";

/// <summary>
/// Convert a long into a DateTime
/// </summary>
public static DateTime FromUnixTime(this Int64 self)
{
  var ret = new DateTime(1970, 1, 1);
  return ret.AddSeconds(self);
}

/// <summary>
/// Convert a DateTime into a long
/// </summary>
public static Int64 ToUnixTime(this DateTime self) 
{
  if (self == DateTime.MinValue) 
    return 0;

  var epoc = new DateTime(1970, 1, 1);
  var delta = self - epoc;
  if (delta.TotalSeconds < 0)
    throw new ArgumentOutOfRangeException(InvalidUnixEpochErrorMessage);

  return (long)delta.TotalSeconds;
}

 

Ähnliche Beiträge

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert