2

I have a string representing ISO UTC date: 2020-06-08T04:00:00.000Z (4am on 8th of July UTC).

I create a date-fns object out of it, so that I can format the displayed string according to needs. So I proceed as follows:

const localDate = parseISO('2020-06-08T04:00:00.000Z');
const formattedDateString = format(localDate, 'MMMM dd, yyyy, EEEE, hh:mm aaa');

However formattedDateString shows in local time (say your browser is in timezone 1Hr ahead of UTC, it shows ...05 AM), but I need to show UTC time (no matter browser's timezone), i.e. ... 4 AM. How do I do that ?

Note: ... indicates omission to keep the example clear

zaggi
  • 870
  • 1
  • 7
  • 24
  • You may find variations to try here https://stackoverflow.com/questions/2891361/how-to-set-time-zone-of-a-java-util-date – Pete Kelley Apr 22 '20 at 10:55
  • @PeteKelley, thanks, but I need it for the Javascript library `date-fns` particularly – zaggi Apr 22 '20 at 10:59
  • There's a document related to time zones on the `date-fns` documentation which should cover what you're looking for: https://date-fns.org/v2.12.0/docs/Time-Zones – Edric Apr 22 '20 at 11:06
  • It seems local time is the default and in order to switch to UTC you need to [do it yourself](https://date-fns.org/v2.12.0/docs/Time-Zones). – Álvaro González Apr 22 '20 at 11:08
  • This was one of my ideas, but the `date-fns-tz` library expects a second parameter timezone, so if you pass sth like `Europe/London` it would partially (!!!) to the job (when the UK deviates from UTC during summer/winter time switching), so again we're facing a 1 hour off part of the year using this approach. Unless there's a 'UTC' parameter, but I cant find any documetation refering to such – zaggi Apr 22 '20 at 11:17
  • You can try my answer to this question here: https://stackoverflow.com/a/61469549/800198 – Sherwin F Apr 27 '20 at 22:35

1 Answers1

1

I ended up adding date-fns-tz library and doing this:

import { parseISO, format } from 'date-fns';
import { utcToZonedTime } from 'date-fns-tz';

const localDate = parseISO('2020-06-08T04:00:00.000Z');
const convertedDate = isLocalTime ? localDate : utcToZonedTime(localDate, 'UTC');
const formattedDateString = isLocalTime
    ? format(convertedDate, 'MMMM dd, yyyy, EEEE, hh:mm aaa EEEE')      // June 08, 2020, Monday, 06:00 AM, GMT+02:00
    : `${format(convertedDate, 'MMMM dd, yyyy, EEEE, hh:mm aaa')} UTC`; // June 08, 2020, Monday, 04:00 AM, UTC

Disclaimer: I didn't find the use of UTC parameter of utcToZonedTime documented (it may be not the recommended way OR just me not finding it in the library docs).

zaggi
  • 870
  • 1
  • 7
  • 24