将Javascript计时器设置为半小时

时间:2013-04-15 19:28:36

标签: javascript timer countdown

我需要制作一个倒数到下午4:30的计时器。到目前为止,我可以将它发送到下午4点或下午5点,但不会介于两者之间。我已经设法解决了这个问题:

<script type="text/javascript">

var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];

var suffix = "AM";

var hoursLeft = 16 - hours;
var minsLeft = 60 - minutes;

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

if (hours >= 18)
{
 document.write("Same day shipping has ended for today.");
} else

if ((n === "Saturday") || (n === "Sunday"))
{
document.write("Same day shipping is not available today.");
} else {

if (hoursLeft === 0) {
    document.write(minsLeft + " minutes left to have your order shipped today!");
} else {
    if (hoursLeft === 1) {
        document.write(hoursLeft + " hour and " + minsLeft + " minutes left to have your order shipped today!");
    } else {
    if ((hoursLeft === 0) && (minsLeft <= 30)){
    document.write(minsLeft + " minute left to have your order shipped today!");
    } else {

    if (minsLeft ===1) {
    document.write (hoursLeft + " hours and " + minsLeft + " minute left to have your order shipped today!");
    } else {


if(minsLeft===60){
minsLeft=0;
hoursLeft++;
n === "Monday";
n === "Tuesday";
n === "Wednesday";
n === "Thursday";
n === "Friday";
}

document.write(hoursLeft  + " hours and " + minsLeft + " minutes left to have your order shipped today!");
}
}
}
}
}

</script>

我需要时间倒计时到下午4:30,但我只知道如何更改“var hoursLeft”将其设置为“16小时”,这让我到下午4点,但无法计算如何到达下午4:30。我以为我会调整“var minsLeft”,但得到了一个奇怪的错误,开始说“2小时和-15分钟左右”。

有人有什么想法吗?

1 个答案:

答案 0 :(得分:1)

作为上述建议的评论者,请在几分钟内完成计算。将您的小时数转换为总分钟数,并确保分钟数在您的参数范围内。

要显示分钟数,只需使用模数运算符即可获得当前小时数的分钟数。

例如,如果还剩185分钟并且您想要显示“剩余3小时5分钟”,

var minutesLeft = 185;
var hours = Math.floor(minutesLeft/60);
var minStr = minutesLeft % 60;
var timeLeft = hours + " hours and " + minStr + " minutes left";

当然,你会想要使用自己的逻辑来避免说“1小时”之类的事情。