0

I'm trying to remove the javascript Date offset, so that the local time a date was recorded in from a given country can be displayed.

I have a test that only works when the timezone is GMT

  describe('.removeLocalDateOffset()', () => {
    it('removes the timezone offset', () => {
      const input = '2017-10-03T08:53:12.000-07:00';
      const result = removeLocalDateOffset(input);
      expect(result.toISOString()).toBe('2017-10-03T08:53:12.000Z');
    });
  });

And the function I want to do the job:

  const removeLocalDateOffset = (date) => {
    const originalDate = new Date(date);
    return new Date(Date.UTC(
      originalDate.getFullYear(),
      originalDate.getMonth(),
      originalDate.getDate(),
      originalDate.getHours(),
      originalDate.getMinutes(),
      originalDate.getSeconds(),
    ));
  }

Any suggestions for how I can do this using the methods of the new Date() object? Ideally not doing a .slice() on a substring.

Test Results. I am currently in GMT:

    Expected: "2017-10-03T08:53:12.000Z"
    Received: "2017-10-03T16:53:12.000Z"
denski
  • 1,768
  • 4
  • 17
  • 35
  • I'm presuming it doesn't work, because `originalDate` is set having calculated the time in respect of the timezone. – denski Dec 20 '19 at 13:40
  • Can you post what is your input date , expected output and error. I am assuming that you want to extract normal date time from this 2017-10-03T08:53:12.000-07:00?? – Prabhjot Singh Kainth Dec 20 '19 at 13:45
  • I suggest you to record the date always as UTC date so you can convert to any location time. The easiest way I know of is using Moment Timezone: https://momentjs.com/timezone/ – desoares Dec 20 '19 at 13:49
  • @desoares If I'd had the luxury of recorded times in UTC, I wouldn't be in this mess! – denski Dec 20 '19 at 13:55
  • Have you tried to use the date integer? – desoares Dec 20 '19 at 14:08
  • You could also taka a look here: https://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc – desoares Dec 20 '19 at 14:15

0 Answers0