Remove timezone information when creating a new Date in Angular
Solution 1
You can not remove timezone information when creating Date
object -- this is a deficiency of the API.
The dates created via various Date
APIs are parsed according to provided timezone (if the given method supports it), or if missing, they assume your local machine's timezone; then internally they're represented as dates relative to the UTC timezone.
Whenever you stringify a date, you implicitly invoke date.toJSON()
which in turn invokes date.toISOString()
, which stringifies to UTC-relative time (hence Z
as the end which stands for Zulu
i.e. UTC).
As far as I can tell there's no method that serializes to ISO-like string but using local timezone.
You could use low-level Date properties to write your own method which serializes back to the local timezone if you really need to, or you could use a library like date-fns
. You could use moment
library, but while very powerful, it's huge so be careful with it.
Solution 2
Yes, it's possible you need to calculate time zone offset and add then add to your date object time sample code is given below.
var d = new Date('2016-06-15 10:59:53.5055');
var timeZoneDifference = (d.getTimezoneOffset() / 60) * -1; //convert to positive value.
d.setTime(d.getTime() + (timeZoneDifference * 60) * 60 * 1000);
d.toISOString()
Comments
-
rst almost 2 years
Following issue, when trying this line of code
console.log(JSON.stringify(new Date('2016-06-15 10:59:53.5055')));
I get
"2016-06-15T08:59:53.505Z"
, I would however expect"2016-06-15T10:59:53.505Z"
How can I remove the timezone from the
new Date
?the issue is, I'm sending this Date via a http-post to an API. In the http.post command, the Date is stringified (right now incorrectly)