0

I have a timezone map with publishing hour in the local zone with news that must define when they should be published on a date using a date picker.

This is a new news article that is initialized with the following:

  • { timeZoneId: 'Europe/Paris, releaseHour: 9, publishingDateTime: undefined } // 9 is the hour GMT+1

I want to know how can I from const now = new Date(), verify if this article should be published today or the next day, the criteria are:

  • Is now before releaseHour? (is 9am GMT+1 in paris already passs or not)
  • If yes, then we should offer the next release slot at 9am GMT+1 + 1 day
  • If no, then we should use the release slot at 9am the same day

How is this possible?

This is how I have tried:

import { isBefore, isEqual } from 'date-fns';
import { utcToZonedTime } from 'date-fns-tz';

export const getNextPublishingDateTime = (now, timeZoneId, releaseHour) => {
  const zoned = utcToZonedTime(now, timeZoneId);
  const releaseTime = new Date(zoned.toISOString());
  releaseTime.setHours(releaseHour, 0, 0, 0);
  if (isBefore(zoned, releaseTime) || isEqual(zoned, releaseTime)) {
    console.log('before');
    return releaseTime;
  }
  releaseTime.setDate(releaseTime.getDate() + 1);
  console.log('after');
  return releaseTime;
};

But the hour returned by utcToZonedTime is not +01:00 offset, instead it is a date at my offset.

I have tried some other ideas, using moment-tz and vanilla Date, I found this task a bit complicated and hope to find help with the JS community as this look to be a normal date comparaison.

Dimitri Kopriwa
  • 13,139
  • 27
  • 98
  • 204

1 Answers1

0

You can use the Intl object and formatToParts method to get the current time in any supported timezone using IANA representative locations. It's reasonably well supported.

E.g.

function getHour(date, loc) {
  let d = new Intl.DateTimeFormat("en-EN", {
    hour: 'numeric',
    hour12: false,
    timeZone: loc
  });
  return d.formatToParts(date)[0].value;
}

let loc = 'Europe/Paris';
let now = new Date();
console.log(`The current hour in ${loc} is ${getHour(now, loc)}.`);

The above is just for illustration, there should be validation of input and return values.

RobG
  • 142,382
  • 31
  • 172
  • 209