Reputation: 8485
Need to find if the user visiting my page is between support hours 8:00am or 16:00pm PST, So if an user from Asia or other Timezone visit the page outside of those hours get a custom label, I can make it work for not timezone involved but I'm having problems with timezone, and the following code always is returning true. any ideas how to achieve this?
import moment from 'moment';
import 'moment-timezone';
const timezone = 'America/Los_Angeles';
const supportStartTime = moment().tz(timezone).hours(8).minutes(0).seconds(0);
const supportEndsTime = moment().tz(timezone).hours(16).minutes(0).seconds(0);
const now = moment();
const isBetweenWorkingHours = now.isBetween(supportStartTime,supportEndsTime);
Upvotes: 1
Views: 682
Reputation: 16875
Seems to be working fine:
var timezone = 'America/Los_Angeles';
var supportStartTime = moment().tz(timezone).hours(8).minutes(0).seconds(0);
console.log(supportStartTime.format());
var supportEndsTime = moment().tz(timezone).hours(16).minutes(0).seconds(0);
console.log(supportEndsTime.format());
var now = moment().tz('EST').startOf('day').hours(10);
console.log(now.format());
var isBetweenWorkingHours = now.isBetween(supportStartTime,supportEndsTime);
console.log(isBetweenWorkingHours);
var now = moment().tz('EST').startOf('day').hours(12);
console.log(now.format());
var isBetweenWorkingHours = now.isBetween(supportStartTime,supportEndsTime);
console.log(isBetweenWorkingHours);
var now = moment();
console.log(now.format());
var isBetweenWorkingHours = now.isBetween(supportStartTime,supportEndsTime);
console.log(isBetweenWorkingHours);
Which produces:
2016-11-06T08:00:00-08:00
2016-11-06T16:00:00-08:00
2016-11-06T10:00:00-05:00
false
2016-11-06T12:00:00-05:00
true
2016-11-06T15:22:48-08:00
true
(I'm in pacific time which is why the time zone comes out that way on the last item.)
console.log(moment().format());
console.log(moment().tz('EST').format());
console.log(moment().tz('UTC').format());
produces:
2016-11-06T16:24:53-08:00
2016-11-06T19:24:53-05:00
2016-11-07T00:24:53Z
These are all the same "now". If you were in EST and ran moment().format()
, you'd get the current time with your timezone attached (line 2). If somebody in UTC ran moment().format()
simultaneously, they'd get "now" relative to their own time zone (line 3). They're both the same "now" since they were run simultaneously, they just have different local representations.
Upvotes: 1