namespace System
{
///
/// DateTimeOffset extension methods.
///
public static class DateTimeOffsetExtensions
{
///
/// The Epoch common to most (all?) Unix systems.
///
public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
///
/// Converts the current Unix time to a DateTimeOffset.
///
/// Seconds since UnixEpoch.
/// DateTimeOffset.
public static DateTimeOffset FromUnixTimeSeconds(this long seconds)
{
#if NETCORE
return DateTimeOffset.FromUnixTimeSeconds(seconds);
#else
DateTimeOffset dateTimeOffset = new DateTimeOffset(DateTimeOffsetExtensions.UnixEpoch);
dateTimeOffset = dateTimeOffset.AddSeconds(seconds);
return dateTimeOffset;
#endif
}
#if !NETCORE
///
/// Converts the current DateTimeOffset to Unix time.
///
/// DateTimeOffset.
/// Seconds since UnixEpoch.
public static long ToUnixTimeSeconds(this DateTimeOffset dateTimeOffset)
{
long unixTimeStampInTicks = (dateTimeOffset.ToUniversalTime() - DateTimeOffsetExtensions.UnixEpoch).Ticks;
return unixTimeStampInTicks / TimeSpan.TicksPerSecond;
}
#endif
}
}