0

I want to show a "Call now" banner on my web site if its between 10am and 6pm PST (everyday).

I'm having trouble coming up with the start and end timestamps.

const open = new Date('12:00:00')
const close = new Date('18:00:00')
const now = new Date();

const isOpen = now.getTime() < close.getTime() && now.getTime() > open.getTime();

chovy
  • 72,281
  • 52
  • 227
  • 295
  • you should try moment.js. – Kungfu Frog Jul 22 '20 at 00:26
  • Does this answer your question? [How to initialize a JavaScript Date to a particular time zone](https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone) – fubar Jul 22 '20 at 00:27
  • Yes, as Chung said you should use Moment.js. There is a function you can probably use isBetween. – Craig Stroman Jul 22 '20 at 00:39
  • how would i do it with moment? I just am having trouble getting 10am pst and 6pm pst as date objects. – chovy Jul 22 '20 at 00:44

2 Answers2

1

Uses TimeZoneOffset between UTC and PST to calculate the hour number.

let timeZoneOffset = -7 // UTC-8 => PST

setInterval(() => {
  let pstHour = (new Date().getUTCHours() + 24 + timeZoneOffset) % 24
  console.log('PST Hour: ', pstHour)
  if (pstHour >=10 && pstHour < 18) console.log("Show 'Call Now' at " + pstHour)
}, 1000)
Sphinx
  • 10,519
  • 2
  • 27
  • 45
1

You can use the Intl.DateTimeFormat constructor and the formatToParts method to determine the time at any location supported by IANA and the host implementation.

First select an IANA representative location that has the timezone offset and daylight saving rules that you want, e.g. for PST/PDT you might chose America/Los_Angeles. Then get the hour from the date at that location and compare the required values:

function getHourAtLoc(loc, date = new Date()) {
  let f = new Intl.DateTimeFormat('en',{hour: '2-digit', hour12: false, timeZone: loc});
  return f.formatToParts(date)[0].value;
}

let hour = getHourAtLoc('America/Los_Angeles');
let isOpen = hour >= 10 && hour < 18; 

console.log('The hour is ' + hour + ' and the shop is ' + (isOpen? 'open' : 'closed') + '.');

This can be extended to other parts of a date and time.

RobG
  • 142,382
  • 31
  • 172
  • 209