65.9K
CodeProject is changing. Read more.
Home

.NET DateTime to Unix Time and Vice Versa

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jul 7, 2015

CPOL
viewsIcon

6733

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