Skip to content Skip to sidebar Skip to footer

.js Help With The Date Object And If/else

ok so im trying to create something where certain elements change based on time of day. that time of day is gotten via system clock. heres my code: var currTime = new Date(); var

Solution 1:

Yes, your problem is your if condition, or perhaps what comes before it.

//display thr and minutes .
var myTime = currHrs + ":" + currMins;

You have created myTime as a string e.g. "12:30". Obviously this is not suitable for comparison with a number.

It won't work with currHrs either because, with your logic, that is never a number less than 12.

I suggest you map out in pseudo code what it is you are trying to accomplish, as it all seems a bit muddled up there.


Solution 2:

You were close. I simply moved a few things around for you.

Edited: Made a few mistakes in my haste. And apologies for syntax error. Fixed now.

var currTime = new Date();

var currHrs = currTime.getHours();
var currMins = currTime.getMinutes();
var currSecs = currTime.getSeconds();

if (currMins < 10) {
  currMins = "0" + currMins;
}

var suffix = "AM";
if (currHrs >= 12) {
  suffix = "PM";
  currHrs = currHrs - 12;
} else if (currHrs == 0) {
  currHrs = 12;
}

var myTime = (currHrs == 0 ? 12 : currHrs) + ":" + currMins + " " + suffix;

if (myTime.match(/(AM)/)) {
  document.getElementById("clock").innerHTML = myTime;    
} else {
  // code here
}

Solution 3:

After this line myTime is a string

var myTime = currHrs + ":" + currMins; 

You're doing a string comparison to an int below.

if(myTime< 12){
    document.getElementById("clock").innerHTML = myTime;    
} else {
    //code here

}

Did you mean to do this ?

if(currHrs < 12){
    document.getElementById("clock").innerHTML = myTime;    
} else {
    //code here

}

Post a Comment for ".js Help With The Date Object And If/else"