4

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)

rst
  • 2,510
  • 4
  • 21
  • 47
  • 1
    Possible duplicate of [Parse date without timezone javascript](https://stackoverflow.com/questions/17545708/parse-date-without-timezone-javascript) – Ronald Haan May 07 '19 at 11:54
  • @RonaldHaan I think not, the problem is, that I don't need a string but really be able to pass it to a http.post which then stringifies it – rst May 07 '19 at 11:56
  • A timezone package like https://momentjs.com/timezone/ might help you. – kacase May 07 '19 at 12:06

2 Answers2

8

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()
6

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.

jakub.g
  • 38,512
  • 12
  • 92
  • 130
  • Would you recommend to simply offset the time with the timezone just before posting it? Seems like to simplest way to go – rst May 07 '19 at 12:31