我在正确计算日期至最接近的星期四和最接近的星期五时遇到问题。控制台显示日期到下一个星期四(23/04)和下一个星期五(24/04),而不是最接近的(16/04),(17/04),而是console.log(date.getDay());正确显示最接近星期四和星期五的时间(4天和5天)。有趣的是,他上周表现出色
<script type="text/javascript">
(function($) {
let compareDate;
let timer;
const nextThursday = () => {
let date = new Date();
date.setHours(12, 0, 0, 0)
const daysToThursday = 7 - date.getDay() + 4;
date.setDate(date.getDate() + daysToThursday);
console.log(date.getDay());
console.log(date)
return date.getTime();
};
const nextFriday = () => {
let date = new Date();
date.setHours(12, 0, 0, 0)
const daysToFriday = 7 - date.getDay() + 5;
date.setDate(date.getDate() + daysToFriday);
console.log(date)
return date.getTime();
};
let countdownDate = nextThursday();
let countDownDate2=nextFriday();
function timeBetweenDates(toDate) {
var now = new Date().getTime();
var difference = countdownDate - now;
var difference2 = countDownDate2 - now;
if (difference <= 0) {
countdownDate = nextThursday();
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$(".days-text").toggle(days > 0);
$(".days").text(days ? days : "");
$(".hours-text").toggle(hours > 0);
$(".hours").text(hours ? hours : "");
$(".minutes-text").toggle(minutes > 0)
$(".minutes").text(minutes ? minutes : "");
$(".seconds").text(seconds);
}
if (difference2 <= 0) {
countDownDate2 = nextFriday();
} else {
var seconds2 = Math.floor(difference2 / 1000);
var minutes2 = Math.floor(seconds2 / 60);
var hours2 = Math.floor(minutes2 / 60);
var days2 = Math.floor(hours2 / 24);
hours2 %= 24;
minutes2 %= 60;
seconds2 %= 60;
$(".days-text2").toggle(days2 > 0);
$(".days2").text(days2 ? days2 : "");
$(".hours-text2").toggle(hours2 > 0);
$(".hours2").text(hours2 ? hours2 : "");
$(".minutes-text2").toggle(minutes2 > 0)
$(".minutes2").text(minutes2 ? minutes2 : "");
$(".seconds2").text(seconds2);
}
}
$(function() {
timer = setInterval(timeBetweenDates, 1000);
})
})(jQuery);
</script>
公式为(dayOfWeek + 7 - currDayOfWeek) % 7
。
const nextThursday = () => {
let date = new Date();
date.setHours(12, 0, 0, 0)
// const daysToThursday = 7 - date.getDay() + 4;
const dayOfWeek = 4 // thursday
date.setDate(date.getDate() + (7 + dayOfWeek - date.getDay() - 1) % 7 + 1);
console.log(date)
return date.getTime();
};
const nextFriday = () => {
let date = new Date();
date.setHours(12, 0, 0, 0)
//const daysToFriday = 7 - date.getDay() + 5;
const dayOfWeek = 5// friday
date.setDate(date.getDate() + (7 + dayOfWeek - date.getDay() - 1) % 7 + 1);
console.log(date)
return date.getTime();
};
阅读此链接的更多信息:https://codereview.stackexchange.com/questions/33527/find-next-occurring-friday-or-any-dayofweek
希望这会有所帮助。