7

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()
Community
  • 1
  • 1
test
  • 2,538
  • 4
  • 35
  • 52

3 Answers3

11

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/

ntziolis
  • 10,091
  • 1
  • 34
  • 50
4

use

var currentDate = new Date();
//get off set from your browser
var offset = Date.getTimezoneOffset();
3

you can use JavaScriptSerializer

string json = new JavaScriptSerializer().Serialize(DateTime.Now);
L.B
  • 114,136
  • 19
  • 178
  • 224
  • I can't even reference System.Web.Script... :/ – test Apr 11 '12 at 15:45
  • @test And I can't see a way to help ones `who can't even reference System.Web.Script` :/ – L.B Apr 11 '12 at 19:12
  • I'm sorry but I cannot find it in the references under 'system' tab. Or should I be searching some where else? – test Apr 11 '12 at 19:19
  • @test Click on the link in my answer. It will show you the namespace and the assembly you need – L.B Apr 11 '12 at 19:22