-4

I have a text field that I need only to display for a certain period of time. I need it to appear after 5pm and stop appearing at 7am daily. The piece of text has been saved as a variable.

How do I do this? Thanks

L.Can
  • 1

1 Answers1

1

You can get time using Date() object and then show and hide your text. e.g

HTML:

<div class="someClass">Your text </div>

JavaScript:

var currentDate = new Date();
var currentTime = currentDate.getHours();

if(currentTime >=17 || currentTime <=7) {
  document.getElementsByClassName('someClass')[0].style.visibility = 'visible';
} else {
  document.getElementsByClassName('someClass')[0].style.visibility = 'hidden';
}
  • 1
    problem with this approach is, it checks against the system date of the client, which the user can easily manipulate – Stultuske Sep 27 '18 at 09:23
  • 1
    @Stultuske it could also be that the user is in a different time zone, too. – VLAZ Sep 27 '18 at 09:25
  • @vlaz which wouldn't be a problem, since 5 o'clock New York time is still 5 o'clock :) – Stultuske Sep 27 '18 at 09:27
  • I heavily suspect the message OP wants to show is something along the lines of "We are closed right now". So if they are based in France, they'd be closed at 18h and shouldn't still be "open" in New York. I guess the message could be, say, "Look out the window and enjoy the scenery, for this is the best time of the day" but I really doubt it. – VLAZ Sep 27 '18 at 09:33
  • If you want actual time, you need to get the time from server itself. That's too have complications as you you have to deal with different time zones. – deepakSharma Sep 27 '18 at 09:36