Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Tip/Trick

.NET DateTime to Unix Time and Vice Versa

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
7 Jul 2015CPOL 6.4K  
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: 

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --