Displaying date consistently, regardless of time zone, in JavaScript & date-fns

Viewed 824

I'm working in NodeJS, which is currently running locally, but will later run somewhere else (a server of unknown location). I'm using the date-fns (2.14.0) and date-fns-tz (1.0.10) libraries. I am in the UK, and right now we are on BST (UTC+1).

I have dates stored in different databases/tables, the dates are saved in different time zones, and I am unable to change this, I have to work with them as I find them.

In this example I'll use 2 dates. I take some action which causes the dates to saved.

The UTC time right now is: 2020-09-18 10:57:00, BST: 2020-09-18 11:57:00. I'm rounding to the nearest minute for these examples.

  1. TableA.Date = 2020-09-18 06:57:00
  2. TableB.Date = 2020-09-18 10:57:00

So I can see that TableA.Date is saved in UTC-4 and TableB.Date is saved in UTC. I believe the UTC-4 is Eastern Daylight Time (EDT) - Boston, US, 'America/New_York' (IANA).

I would like to display all dates in UTC in my app, to provide users a consistent view, and the users will be viewing from all over the world.

Is this even possible..?

Update

I have this now:

function test (dateStr, tz) {
  const toUtc = dateFnsTz.zonedTimeToUtc(dateStr, tz)
  const toZonedTime = dateFnsTz.utcToZonedTime(toUtc, 'UTC')
  const formatted = dateFnsTz.format(toZonedTime, 'dd MMM yyyy HH:mm:ss', 'UTC')

  console.log(formatted)

  return null
}

test('2020-09-18 06:57:00', 'America/New_York') // 18 Sep 2020 10:57:00
test('2020-09-18 10:57:00', 'UTC')              // 18 Sep 2020 10:57:00
test('2020-09-18 11:57:00', 'Europe/London')    // 18 Sep 2020 10:57:00

Is this going to work consistently, or will this break daylight saving or anything else..?

0 Answers
Related