0

I'm trying to hide/display an element based on time.

The only thing is that this needs to be regardless of time zone.

For example, if I have an event at 8 AM New York time, how can I hide an element at that time (no matter where the user is located)?

I'm adding this starting sandbox: https://codesandbox.io/s/ny-event-time-rp34ml?file=/src/index.js

Thanks!

Harel
  • 21
  • 2
  • [Convert the current time to the specific timezone](https://stackoverflow.com/questions/10087819/convert-date-to-another-timezone-in-javascript) and then check if it is past that time. – Samball Jun 03 '22 at 14:35
  • Please provide enough code so others can better understand or reproduce the problem. – Community Jun 03 '22 at 18:54

1 Answers1

1

You need to take current time,then convert it to your target timezone(New_York), then check if user's current time is in your events range and...

Keep in mind that this only works if user's clocks on him/her device is set correctly, Otherwise you need to get current time through an api (there are some free APIs that does this for you but if you have a server/host, I suggest making one for yourself to get your job done)

More explanation provided as comments

// function to convert current user local time to another time zone
function getTime(timeZone, date = new Date()) {
  return new Date(
    date.toLocaleString("en-US", {
      timeZone,
    })
  );
}
const nyc = getTime("America/New_York"); // current New_York date
// get current day/month/year
const [month, day, year] = nyc.toLocaleString("en-US").split(", ")[0].split("/");

// get current time
const currentTime = getTime("America/New_York").getTime();
/* you can change the event time here
    e.g. if you wanna event start at 10:05:30 pm try this
    const eventTime = new Date(+year, month - 1, +day, 22, 05, 30).getTime(); */
const eventTime = new Date(+year, month - 1, +day, 8, 0, 0).getTime();
const beforeEvent = eventTime - 900000; // 15 min before event start
const afterEvent = eventTime + 3600000; // 60 min after event start

const beforeElement = document.querySelector(".before");
const startElement = document.querySelector(".start");
const afterElement = document.querySelector(".after");
// hides all elements by default
[beforeElement, startElement, afterElement].forEach((e) => (e.style.display = "none"));

// do stuff before event starts
if (currentTime < beforeEvent) {
  // display beforeElement before event starts
  beforeElement.style.display = "block";
}
// do stuff during event
if (currentTime >= beforeEvent && currentTime <= afterEvent) {
  // display startElement during event
  startElement.style.display = "block";
}
// do stuff after event ends
if (currentTime > afterEvent) {
  // display afterElement after event ends
  afterElement.style.display = "block";
}
<p class="before">Before Event</p>
<p class="start">Event Started</p>
<p class="after">After Event</p>
Alireza
  • 608
  • 2
  • 5
  • 11