0

I am working on a locale news application.

Readers will get the news close to their place if you are in Paris, your local time zone is Europe/Paris, and we release news at 9am every morning.

We want to allow before 9am publishing

How can I check if 9am Europe/Paris is after or equal to new Date() (no matter what the client zone is) in JavaScript?

  • In this end I will add an offset of -1hours, to block news posting at 8am
  • we already have that check server side, it's mainly for alerting the user that it will posted the next day
Dimitri Kopriwa
  • 13,139
  • 27
  • 98
  • 204

2 Answers2

0

When dealing with multiple time zones. You should always compare in UTC (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours). The idea is

  1. Use "new Date('August 19, 1975 09:00:00 GMT+01:00');" to create a current time in Paris timezone.
  2. Then use "date.getUTCHours();" to get hours in UTC
  3. Then compare this value to client timezone hours (in UTC).

var parisTime = new Date('March 20, 2020 09:00:00 GMT+01:00');
var parisInUTC = parisTime.getUTCHours();

var ukTime = new Date();
var ukInUTC = ukTime.getUTCHours();

console.log(parisTime);
console.log(parisInUTC);
console.log(ukTime);
console.log(ukInUTC);
console.log(ukInUTC < parisInUTC);
Alex - Tin Le
  • 1,982
  • 1
  • 6
  • 11
  • Yes but I have as input arguments `timeZone = "Europe/Paris"` and `timeZoneReleaseHour = 9`, the `9` correspond to `9am` paris, I don't even know how to initiate this UTC – Dimitri Kopriwa Mar 20 '20 at 15:43
  • You can create new Paris time by using new Date('August 19, 1975 23:15:30 GMT+07:00'); – Alex - Tin Le Mar 20 '20 at 15:46
  • How do I get `August 19, 1975 09:00:00 GMT+01:00` starting from the provided date, it should be the same date (not locale date), eg 2020-01-01 05:00:+07:00 should also be 2020-01-01 09:00:+01:00 – Dimitri Kopriwa Mar 20 '20 at 15:47
  • From your database, you should be able to tell at what time the news is created? What value do you have? – Alex - Tin Le Mar 20 '20 at 15:50
  • I have tried `const todayPublishDate = new Date(value.getFullYear(), value.getMonth(), value.getDate(), timeZoneReleaseHour, 0, 0, 0);` but it gives me `Sat Mar 21 2020 09:00:00 GMT+0700 (Indochina Time)` – Dimitri Kopriwa Mar 20 '20 at 15:56
  • what is todayPublishDate? I thought you want to compare Paris 9AM with current client Time? – Alex - Tin Le Mar 20 '20 at 16:00
  • todayPublishDate is the publishing date offered to the user client side, if we are now after 9am today, then next publish date is tomorrow 9am (again paris time) – Dimitri Kopriwa Mar 20 '20 at 16:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210013/discussion-between-dimitri-kopriwa-and-alex-tin-le). – Dimitri Kopriwa Mar 20 '20 at 16:13
0

You could use moment-timezone

moment.tz("09:00","HH:mm","Europe/Paris").isSameOrAfter(new Date())
Robert
  • 19,800
  • 5
  • 55
  • 85