2

I am using a web service which returns me JSON data.

one of the value in that JSON data is datetime.

1421788745000 - This is the value returned for that datetime field.

When I tried to convert that value into DateTime (using below code), it returns me 01/02/0001 3:29:38 PM.

 foreach(dynamic jResult in jsonResult["twtDetails"])
                    {                        
                        DateTime date = new DateTime(long.Parse("1421788745000"));
                        DateTime dt = new DateTime(createdAtTime);
                    }

But when I tried to parse the same value using following javascrit code (using this site - http://jsfiddle.net/ ), I got a valid date : Tuesday 20th Jan 2015

alert(new Date(1421788745000).toUTCString());

Can somebody tell me what is the correct C# code for this ?

Relativity
  • 6,690
  • 22
  • 78
  • 128
  • 1
    Related: [How do you convert epoch time in C#?](http://stackoverflow.com/questions/2883576/how-do-you-convert-epoch-time-in-c) Though, JavaScript timestamps are in [milliseconds](https://msdn.microsoft.com/en-us/library/system.datetime.addmilliseconds.aspx). – Jonathan Lonowski Jan 20 '15 at 23:04

3 Answers3

0

There is some magic with the year 1970, as far as I remember.

Try this:

public DateTime ConvertDate(long unixTime)
{
    var date= new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return date.AddSeconds(unixTime);
}

Maybe, you may take a deeper look at Unix Time.

MrMAG
  • 1,194
  • 1
  • 11
  • 34
0

The constructor for C# DateTime and JavaScript Date are different. JavaScript Date expects milliseconds since the "Unix Epoch" of 1/1/1970. This code should work for you in C#:

    var dt = new DateTime(1970,1,1).AddMilliseconds(1421788745000);
MatthewG
  • 8,583
  • 2
  • 25
  • 27
0

Have you tried using JavaScriptSerializer.Deserialize method?

Mike Burdick
  • 838
  • 6
  • 5
  • 1
    This would be better as a comment, not an answer. – Soner Gönül Jan 21 '15 at 06:44
  • I used JavaScriptSerializer.Deserialize. But I dont want to create a data contract to build the response...and I used dynamic instead. So the datetime field is coming as string. – Relativity Jan 21 '15 at 14:57