Javascript parsing json date timezone mismatch causes wrong date to display
-
19-06-2021 - |
Domanda
The displaying of a javascript-parsed date is different based on the timezone of the machine loading the page.
SERVER TIME: EST
MACHINE #1 TIME: EST - shows proper date
MACHINE #2 TIME: EST - shows proper date
MACHINE #3 TIME: PST - shows one day earlier
MACHINE #4 TIME: PST - shows one day earlier
I'm wondering how to parse a JSON date such that the time zone will not be a factor. Here's my current code:
var jsonDate = "/Date(1341633600000)/";
var formattedDate = new Date(parseInt(jsonDate.substr(6)));
return formattedDate.getMonth() + 1 + "/" + formattedDate.getDate() + "/" + formattedDate.getFullYear();
What's the best approach to ignore the timezone offset?
Soluzione
The problem has nothing to do with parsing the dates. You're sending a UTC timestamp to the client, and the client is (correctly) reflecting the date in local terms.
You can always use the getUTCxxx
methods (getUTCDate()
, getUTCMonth()
, getUTCFullYear()
) to make the page show the date as UTC. Alternatively, you could convert the timestamp to a date string on the server in its local time zone, so that the client time zone wouldn't figure into it at all.