Similar questions have been asked but for whatever reason I just can't wrap my head around this. I want a user anywhere in the world to see whether a shop is open or closed on my site. The shop's hours are 8am-8pm MF, and 8am-7pm Sat-Sun.
So basically the code needs to grab the users local time and compare that to the current time in CT, and see if the shop is open. This is made a bit more complicated by the fact that if its 7pmCT on Tuesday night, it could be Wednesday morning in a far eastern time zone, so now you need to compare the days too.
All the searching I did found bits and pieces of similar questions/answers but I just can't wrap my head around how to put it all together to come up with a solution. I started by trying this:
var currTimeTokyo = moment.tz(moment(), 'Asia/Tokyo').format();
var currTimeCT = moment.tz(moment(), 'America/Chicago').format();
console.log(currTimeTokyo);
console.log(currTimeCT);
and that gives:
2021-10-30T00:51:42+09:00
2021-10-29T10:51:42-05:00
Those are correct, but now how do I compare to today's open/closed hours? I need to check if the Tokyo time is between open and close in CT, but the open/close times change depending on what day it is, and Tokyo could be a different day from CT anyways. How would you account for all of that?
UPDATE: I found something that worked and posted as an answer.
I don't know moment.js and I think it is already announced deprecated (day.js or luxon would be current alternatives) so I can't give you the proper syntax, but I try to help with the logic.
I looked into Luxon as Corrl suggested and I came up with this, which I think solves my problem.
// open hours are M-F 8am-8pm, Sat-Sun 8am-7pm (all times CT)
var hours = [
{ day: 'Sunday', open:8, close:19 },
{ day: 'Monday', open:8, close:20 },
{ day: 'Tuesday', open:8, close:20 },
{ day: 'Wednesday', open:8, close:20 },
{ day: 'Thursday', open:8, close:20 },
{ day: 'Friday', open:8, close:20 },
{ day: 'Saturday', open:8, close:19 }
];
var isOpen = false;
var local = luxon.DateTime.local(); // get current time in local tz
var localInCT = local.setZone("America/Chicago"); // rezone to CT without changing timestamp;
hours.forEach(function(item, index){
if (index === localInCT.weekday && localInCT.hour >= item.open && localInCT.hour < item.close) {
isOpen = true;
}
});
console.log(isOpen);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.