Skip to content

Instantly share code, notes, and snippets.

@KennyLisc
Forked from peterfoot/DateTimeOffsetExtensions.cs
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save KennyLisc/bc13b54f62c25cb842a5 to your computer and use it in GitHub Desktop.

Select an option

Save KennyLisc/bc13b54f62c25cb842a5 to your computer and use it in GitHub Desktop.

Revisions

  1. @peterfoot peterfoot created this gist Jul 23, 2015.
    37 changes: 37 additions & 0 deletions DateTimeOffsetExtensions.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    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);
    }
    }
    }