gpt4 book ai didi

javascript - 倒计时值返回 0

转载 作者:行者123 更新时间:2023-11-28 05:38:37 25 4
gpt4 key购买 nike

我必须设置每个月 15 号的倒计时。我能够成功获得倒计时 15 日所需的差值。

计算差异后,我计算天、小时、分钟、秒。

除天数之外的所有其他值都返回 0

export default React.createClass({
tick: function() {
var currentDate = new Date();
var date_till_15 = new Date();

if (currentDate.getDate() < 15) {
var days_till_15 = 15 - currentDate.getDate();
date_till_15 = new Date(date_till_15.setDate(currentDate.getDate() + days_till_15 ));
} else if(currentDate.getDate() > 15){
date_till_15 = new Date(date_till_15.setMonth(currentDate.getMonth() + 1));
date_till_15 = new Date(date_till_15.setDate(15));
}

var difference = date_till_15 - currentDate;
var daysLeft = 0, hoursLeft = 0, minutesLeft = 0, secondsLeft = 0;

if (difference > 0) {
daysLeft = Math.floor( difference / (1000*60*60*24) );
difference -= daysLeft * (1000*60*60*24);
hoursLeft = Math.floor( difference / (1000*60*60) );
difference -= hoursLeft * (1000*60*60);
minutesLeft = Math.floor( difference / (1000*60) );
difference -= minutesLeft * (1000*60);
secondsLeft = Math.floor( difference/1000 );

this.setState({
days: daysLeft,
hours: hoursLeft,
minutes: minutesLeft,
seconds: secondsLeft
});
} else {
clearInterval( this.timeInterval );
this.setState({ expired: true });
}
},

componentDidMount: function(){
this.timeInterval = setInterval( this.tick.bind(this), 1000);
},

render() {
return (
<div>
{this.state &&
<div>
<div>{this.state.days}</div>
<div>{this.state.minutes}</div>
</div>
}
</div>
)
}
});

最佳答案

试试这个:

console.log(getTimeToNext(15));

function getTimeToNext(dayOfMonth) {
var currentDate = new Date();
var target;
if (currentDate.getDate() < dayOfMonth) {
target = new Date(
currentDate.getFullYear(),
currentDate.getMonth(),
dayOfMonth, 0, 0, 0, 0);
} else {
var currentMonth = currentDate.getMonth();
if (currentMonth === 11) {
target = new Date(
currentDate.getFullYear() + 1,
0,
dayOfMonth, 0, 0, 0, 0);
} else {
target = new Date(
currentDate.getFullYear(),
currentMonth + 1,
dayOfMonth, 0, 0, 0, 0);
}
}

var delta = target - currentDate;
var daysLeft = Math.floor(delta/(1000*60*60*24));
delta -= daysLeft * (1000*60*60*24);
var hoursLeft = Math.floor(delta/(1000*60*60));
delta -= hoursLeft * (1000*60*60);
var minutesLeft = Math.floor(delta/(1000*60));
delta -= minutesLeft * (1000*60);
var secondsLeft = Math.floor(delta/(1000));

return {
days: daysLeft,
hours: hoursLeft,
minutes: minutesLeft,
seconds: secondsLeft};
}

关于javascript - 倒计时值返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39133233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com