Reputation: 1376
I have an MVC5 Web Application as web interface for my time recording app. My android app sends its times as string to server, there I parse them to .NET DateTime and store it in Database. When I load the time records again and create a JavaScript array I get one additional hour added. I already tried a lot but this post seems to solve the problem: stackoverflow
new Date(date.valueOf() + date.getTimezoneOffset() * 60000);
My question is: Is this the correct way to do? I don’t need any culture or time zones for time recording. A time record that starts at 6 am and ends at 6pm has always this values. Actually it even MUST have this values! Isn’t there a way to tell the JavaScript Date that it should do nothing with my time? Just hold the value I set to it?
UPDATE/Extension: My web inteterface is a MVC5 application and the communication with android phones is done with a WCF service. To make the the code I posted above run I kicked out the JavaScriptSerializer and wrote the JSON array with StringBuilder. This gave me the possibility to include the snipped posted above and let it be executed on the client. I also tried all DateTime.Kind's (local, unspecified and UTC) in combination with the JavascriptSerializer but with no success.
Again, I need unmodified datetimes on client side.
With the answer of Matt I now see three options:
Cheers, Stefan
Upvotes: 1
Views: 2255
Reputation: 4814
It's difficult to tell from the question, but you need to be working with Coordinated Universal Time (UTC) when storing your dates - it just makes things easier to work with later on. Javascript dates all work in local time, but if the server is sending down UTC time, you can easily convert.
So if the server send down (e.g. in JSON), your date value like "2014-03-09T21:25:05.937Z"
, then you can get it in the user's local time using:
var localDate = new Date(Date.parse("2014-03-09T21:25:05.937Z"))
This gives localDate
a value of Mon Mar 10 2014 10:25:05 GMT+1300 (New Zealand Daylight Time)
(in my time zone).
The crucial bit is the 'Z' at the end of the date string. This marks it as Zulu-time/UTC ... from there, javascript can convert for you just fine.
If you are using a WebAPI, then the following should help get things going, even with stored local dates:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
Upvotes: 1