Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

.NET DateTime to Unix Time and Vice Versa

0.00/5 (No votes)
7 Jul 2015 1  
Tip about converting .NET DateTime to Unix double timestamp and vise versa - on .NET

Diffrences (In Short)

The main diffrence in those two formats (Windows and Unix) is that Unix counts seconds since the 1.1.1970 while Windows considers its start time as 1.1.0001.

You can check the DateTime with DateTime.MinValue.

Unix Time: https://en.wikipedia.org/wiki/Unix_time

DateTime.MinValuehttps://msdn.microsoft.com/en-us/library/system.datetime.minvalue(v=vs.110).aspx

Those functions convert the .NET DateTime Value to Unix Double and vice versa: 

public static DateTime Covert(double unixTime)
{
    System.DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    return result.AddSeconds(unixTime).ToLocalTime();
}

public static long Covert(DateTime dotNetTime)
{
    var result = (dotNetTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
    return (long)result;
}

History

  • 7th July, 2015: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here