Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
namespace InTheHand
{
/// <summary>
/// Helper class for DateTimeOffset.
/// </summary>
public static class DateTimeOffsetHelper
{
private static DateTimeOffset dt = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <summary>
/// Converts a Unix time expressed as the number of seconds that have elapsed since 1970-01-01T00:00:00Z to a DateTimeOffset value.
/// </summary>
/// <param name="seconds">A Unix time, expressed as the number of seconds that have elapsed since 1970-01-01T00:00:00Z (January 1, 1970, at 12:00 AM UTC).
/// For Unix times before this date, its value is negative.</param>
/// <returns>A date and time value that represents the same moment in time as the Unix time. </returns>
public static DateTimeOffset FromUnixTimeSeconds(long seconds)
{
return dt.AddSeconds(seconds);
}
/// <summary>
/// Returns the number of seconds that have elapsed since 1970-01-01T00:00:00Z.
/// </summary>
/// <param name="date">The DateTimeOffset value.</param>
/// <returns>The number of seconds that have elapsed since 1970-01-01T00:00:00Z. </returns>
/// <remarks>Unix time represents the number of seconds that have elapsed since 1970-01-01T00:00:00Z (January 1, 1970, at 12:00 AM UTC).
/// It does not take leap seconds into account.
/// <para>This method first converts the current instance to UTC before returning its Unix time.
/// For date and time values before 1970-01-01T00:00:00Z, this method returns a negative value.</para></remarks>
public static long ToUnixTimeSeconds(this DateTimeOffset date)
{
return Convert.ToInt64(date.Subtract(dt).TotalSeconds);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment