Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript DATE and C# date - what is the best solution?

I am getting a date from server side C# using the following code:

DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = (DateTime)c.ccdTimestamp2;
long x = new TimeSpan(d2.Ticks - d1.Ticks).TotalMilliseconds;

When I get my code on the javascript side:

function (timestamp) {
    alert("testing :" + new Date(timestamp))
}

This gives me a fully formatted date but it does not bring the time of my timezone since if it is 17.15 here, it provides me with 19.15 GMT +2 !

At first I simply tried to pass my c# timestamp, without any of the code above and found this question: How do I format a Microsoft JSON date? But I have no idea what JSON is and I couldn't derive what I can do! Is it easier to use JSON? If so can anyone guide me? Thank you very much


Edit: The Solution - I did not use universal time on the server side. I left server side code as it is. All I did is this:

new Date(timestamp).toUTCString()
like image 663
test Avatar asked Apr 11 '12 15:04

test


3 Answers

What you should do is:

  • Always use UTC times on the server
  • Send UTC times to the browser as unit time stamps as you do now
  • Convert the time stamp to local time in the browser

The timestamp used represents: 2012-04-11T15:46:29+00:00:

var d = new Date ( 1334159189000 );
// gives you back 2012-04-11T15:46:29+00:00 in a slightly different format, but the timezone info matches UTC/GMT+0
d.toUTCString();
// gives you back your local time
d.toLocaleString();

Just created a jsfiddle to show that it does what it is supposed to:
http://jsfiddle.net/t8hNs/1/

like image 149
ntziolis Avatar answered Oct 28 '22 23:10

ntziolis


use

var currentDate = new Date();
//get off set from your browser
var offset = Date.getTimezoneOffset();
like image 33
Kasidesh Yontaradidthaworn Avatar answered Oct 29 '22 01:10

Kasidesh Yontaradidthaworn


you can use JavaScriptSerializer

string json = new JavaScriptSerializer().Serialize(DateTime.Now);
like image 39
L.B Avatar answered Oct 29 '22 00:10

L.B