Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a Unix timestamp to DateTime and vice versa?

There is this example code, but then it starts talking about millisecond / nanosecond problems.

The same question is on MSDN, Seconds since the Unix epoch in C#.

This is what I've got so far:

public Double CreatedEpoch {   get   {     DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();     TimeSpan span = (this.Created.ToLocalTime() - epoch);     return span.TotalSeconds;   }   set   {     DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();     this.Created = epoch.AddSeconds(value);   } } 
like image 901
Mark Ingram Avatar asked Oct 30 '08 10:10

Mark Ingram


People also ask

How do I convert timestamp to DateTime in darts?

To get date time from a given timestamp, we can use the DateTime. fromMillisecondsSinceEpoch or DateTime. fromMicrosecondsSinceEpoch constructor. We have to multiply the timestamp input by 1000 because DateTime.

How do I convert timestamp to date and time?

Convert timestamp to date If you have a list of timestamp needed to convert to date, you can do as below steps: 1. In a blank cell next to your timestamp list and type this formula =(((A1/60)/60)/24)+DATE(1970,1,1), press Enter key, then drag the auto fill handle to a range you need.


1 Answers

Here's what you need:

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp ) {     // Unix timestamp is seconds past epoch     DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);     dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime();     return dateTime; } 

Or, for Java (which is different because the timestamp is in milliseconds, not seconds):

public static DateTime JavaTimeStampToDateTime( double javaTimeStamp ) {     // Java timestamp is milliseconds past epoch     DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);     dateTime = dateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();     return dateTime; } 
like image 144
ScottCher Avatar answered Oct 09 '22 08:10

ScottCher