我在用javascript格式化日期并提前添加其他日期时遇到问题。
该代码运行良好,但格式很丑陋,您能检查一下我的代码并告诉我在代码中的其他日子应该放在哪里吗。
<p id="advancedate"></p>
<script>
function addWorkDays(startDate, days) {
if(isNaN(days)) {
return
}
if(!(startDate instanceof Date)) {
return
}
var dow = startDate.getDay();
var daysToAdd = parseInt(days);
if (dow == 0)
daysToAdd++;
if (dow + daysToAdd >= 6) {
var remainingWorkDays = daysToAdd - (5 - dow);
daysToAdd += 2;
if (remainingWorkDays > 5) {
daysToAdd += 2 * Math.floor(remainingWorkDays / 5);
if (remainingWorkDays % 5 == 0)
daysToAdd -= 4;
}
}
startDate.setDate(startDate.getDate() + daysToAdd);
return startDate;
}
var today = new Date(),
month = today.getMonth(),
date = today.getDate(),
day = today.getDay();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var weeks = ["Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("advancedate").innerHTML = addWorkDays = (weeks[day] + "," + months[month] + " " + date ); //Saturday,May 11
//document.getElementById("advancedate").innerHTML = addWorkDays(today, 14); //Wed May 15 2019 09:51:41 GMT+0800
</script>
答案 0 :(得分:0)
首先,如果您不希望addWorkDays
对输入的日期进行变异,我建议添加以下内容
function addWorkDays(startDate, days) {
if(isNaN(days)) {
return
}
if(!(startDate instanceof Date)) {
return
}
// avoid changing the passed in Date object
startDate = new Date(startDate);
var dow = startDate.getDay();
var daysToAdd = parseInt(days);
/// ... rest of your code
}
但这不是必需的,取决于使用情况
现在可以正确使用它(无论上面的更改如何)
var today = new Date();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var weeks = ["Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var future = addWorkDays(today, 14),
month = today.getMonth(),
date = today.getDate(),
day = today.getDay();
document.getElementById("advancedate").innerHTML = (weeks[day] + "," + months[month] + " " + date ); //Saturday,May 11
答案 1 :(得分:-1)