user3387566
user3387566

Reputation: 167

toLocaleTimeString() returns 24hr or 12hr time?

My code works fine as far as I can tell (though I'm open to improvements as an amateur coder) but there is one machine at my office that seems to not work the same as all others.

On that PC my script works for FireFox but on Chrome it doesn't.

The code: [depending on time of day and whether it is a weekend or weekday it hides or displays two divs]

var d = new Date();
var t = d.toLocaleTimeString();
var day = d.getDay()%6;

if (t < "08:30:00" || t > "17:30:00" || day == 0 ) {
    document.getElementById("div1").style.display = "none";
    document.getElementById("div2").style.display = "inline";
  } else {
    document.getElementById("div1").style.display = "inline";
    document.getElementById("div2").style.display = "none";
} 

The problem I'm facing is in Chrome on this particular computer it is going wrong and display/hiding the opposite divs that are supposed to display/hide.

My question:

Am I calculating the time right/using the right functions and such?

Is my approach compatible with modern fairly update-to-date browsers?

Thank you.

Upvotes: 0

Views: 623

Answers (1)

Max Meijer
Max Meijer

Reputation: 1729

toLocaleTimeString() will have another implementation in different locales. You shouldn't use it to check the time. Only use it to show the time to the user.

You might want to take a look at this.

You could use getHours() and getMinutes() to check the time.

You can also do this:

var t1 = new Date(d);
t1.setHours(8);
t1.setMinutes(30);
t1.setSeconds(0);
var t2= new Date(d);
t2.setHours(17);
t2.setMinutes(30);
t2.setSeconds(0);
var day = d.getDay()%6;

if (d < t1 || d > t2 || day == 0 ) {
    document.getElementById("div1").style.display = "none";
    document.getElementById("div2").style.display = "inline";
  } else {
    document.getElementById("div1").style.display = "inline";
    document.getElementById("div2").style.display = "none";
} 

Upvotes: 2

Related Questions