Calculating Future Epoch Time in C#

UnkwnTech picture UnkwnTech · May 25, 2009 · Viewed 18.9k times · Source

I was able to find example code to get the current timestamp in Linux Epoch (Seconds since Midnight Jan 1st 1970), however I am having trouble finding an example as to how to calculate what the Epoch will be in the future, say for example 10 minutes from now, so how can I calculate a future time in Linux Epoch?

Answer

Noldorin picture Noldorin · May 25, 2009

This extension method should do the job:

private static double GetUnixEpoch(this DateTime dateTime)
{
    var unixTime = dateTime.ToUniversalTime() - 
        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    return unixTime.TotalSeconds;
}

And you can use it as such:

var unixTime1 = DateTime.Now.GetUnixEpoch(); // precisely now
var unixTime2 = (DateTime.Now + new TimeSpan(0, 10, 0)).GetUnixEpoch(); // 10 minutes in future

Note that you need to deal with all date-times in UTC (Universal Time), since that's how the start of the Unix Epoch is defined.