开发者

.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:

开发者_如何学Cvar 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;
  }
  if (currHrs == 0) {
  currHrs = 12;
  }



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



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

}

problem im having is that the time isnt being written at all in the html "clock" div. i know it works because if i take out the 'if' and just do the document.write etc, its prints to screen.

im assuming that the problem is the myTime > 12 part. if i do '>' or '<' , it still doesnt work.

what i want is that say for example, if its before 12pm something happens, etc. i just dont know how to target for example, morning time from noon, night etc.

any ideas, etc ill gladly appreciate.

thanks in advanced.


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.


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
}


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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜