Skip to content
Advertisement

Time Based Links in HTMLJavaScript

I’m working on game right now that will have an Item Shop. I thought it would be fun that you couldn’t just walk in at an untimely hour.

I made, with a bit of help, this random script (I’m not really sure if this will help) that will let you enter the shop 90% percent of the time. :

<script language="JavaScript"> 
    var result = (Math.random()*10)
    var a = document.createElement('a');

if(result >= 9)
{
    var linkText = document.createTextNode("Enter The Shop");
    a.id = "OpenShop";
    a.appendChild(linkText);
    a.title = "A place to buy weapons and stuff!";
    a.href = "open.html";
    document.body.appendChild(a);
    }
    else
    {
    var linkText = document.createTextNode("Don't Enter The Shop");
    a.id = "ClosedShop";
    a.appendChild(linkText);
    a.title = "A place to buy weapons and stuff!";
    a.href = "notopen.html";
    }  
    document.body.appendChild(a);

I was wondering if it would be possible to change a few lines and make it to where the shop could be open from 9 a.m.-8 p.m. but to be closed for the rest of the day.

(Before 9 a.m. and after 8 p.m. the shop needs to be closed.)

EDIT: I am also unsure how to center this.

Advertisement

Answer

See this similar question asked by Yanlu. In your case you would check if the current hour is at least 9 but less than 20.

Basing my answer on Nev‘s answer, you should do:

var currentHours = new Date.getHours();
if (currentHours >= 9 && currentHours < 20) {
…
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement