Reputation: 3272
I am having one website in which it has functionality to Login with specific timezone regardless what's the timezone on client side.
Now, In website when user selects a date in dialog.I am sending it to server side using JSON.stringify with several other properties.
But whenever it is received at server side date is changed.
Example :-
I logged in using (+05 : 30) India time zone "01/08/2015 00:00:00" and server is having Casablanca Timezone.
When the date is received at server side the date is reduced by One "31/08/2015".
I think it is because of timezone conversion.
I already checked following link :-
JSON Stringify changes time of date because of UTC
I already tried that answer :- https://stackoverflow.com/a/1486612/2592727
But i am unable to understand how that formula works. So it's better to get more details and work with some specific solution.
Requirement :-
I am allowing user to select only date. I want same date to be received over server side.
How can i accomplish this? Please describe with more details if possible.
Is there any simple way to avoid this collision?
Upvotes: 1
Views: 6078
Reputation: 700730
The JSON.stringify
method stored the date as UTC in the string, and when you parse that in .NET you will get a DateTime
that contains the exact same point in time, but converted to the local time of the server.
You can handle this in two ways, you can either convert the time back to the original time zone, or you can avoid using the Date
data type.
Converting to the original time zone of course requires you to know what the time zone is. Example:
var zone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime userTime = TimeZoneInfo.ConvertTimeFromUtc(date.ToUniversalTime(), zone);
To avoid using the Date
type, you would format the date into a string before serialising it. Example:
var s = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
On the server side you would parse the string using the same format:
DateTime userTime = DateTime.ParseExact(date, "yyyy-M-d", CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 1045
Use the format yyyy-mm-dd hh:mm:ss and you will never get this ever again, regardless of timezone
Upvotes: 1