0

I have a date I know is stored in Central Time. It has the following format: 2017-11-19T23:39:35.280000. I want to turn this into an ISO-formatted date in the current timezone. I got it to work when simply creating a new Date() -- but then when I subsequently call .toISOString(), it goes haywire. Here's the code:

function convertCentralToLocal() {
  const centralOffset = 360;
  const dateInCentralMs = new Date('2017-11-19T23:39:35.280000').getTime();
  const now = new Date();
  const localOffset = now.getTimezoneOffset();

  // this works: Sun Nov 19 2017 23:39:35 GMT-0600 (CST)
  const d = new Date(dateInCentralMs + ((centralOffset - localOffset) * 60000));

  // this seems to give the date six hours off: 2017-11-20T05:39:35.280Z
  const iso = d.toISOString();
}

Is it an issue with GMT? I'm feeling lost.

Andrew Gibson
  • 411
  • 6
  • 17
  • "CST" I guess is US Central Standard Time, not Cuba Standard Time or China Standard Time. The US CST is UTC -0600. Don't use the built-in parser, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) The *toISOString* method is always UTC, both strings represent the same moment in time but in different timezones. Also see [*Where can I find documentation on formatting a date in JavaScript?*](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – RobG Nov 21 '17 at 10:40

1 Answers1

0

It's true that ISO 8601 doesn't define a fixed timezone to represent the Date/Time, but it does define symbols to represent the timezone and a few date/time formats as well:

Date and Time Formats

TZD = time zone designator (Z or +hh:mm or -hh:mm)

Date.prototype.toISOString()

At MDN you can read that the timezone will be always zero UTC offset:

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

It's a particularity from Date.toISOStringMethod. On the same way that a fixed format was chosen (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ), it had been chosen a specific timezone to ISO representation.

To workaround this particularity, you could implement the method toISOString() as shown in this link below or just use your own example.

Gabriel Heming
  • 1,100
  • 10
  • 30