Monday, July 23, 2007
C# DateTime to/from Unix Epoch
Converting Unix timestamp(Epoch) to/from DateTime object in C#:
public static readonly DateTime JAN_01_1970 =
DateTime.SpecifyKind(new DateTime(1970, 1, 1, 0, 0, 0), DateTimeKind.Utc);
// Get Unix Timestamp for given DateTime
public static long SecondsFromEpoch(DateTime date)
{
DateTime dt = date.ToUniversalTime();
TimeSpan ts = dt.Subtract(JAN_01_1970);
return (long)ts.TotalSeconds;
}
// Given Unix Timestamp, get DateTime
public static DateTime EpochToDate(long secFromEpoch)
{
return JAN_01_1970.AddSeconds(secFromEpoch);
}
Subscribe to Posts [Atom]