在美国,顿悟的基督徒节日发生在1月2日至1月8日(含)的星期日。我正在尝试使用Javascript来查找它所处的日期。看起来它应该可行,但我什么都没得到:
var startDate = new Date(2018,0,2);
var endDate = new Date(2018,0,8);
var epiphanyUS = new Date();
while (startDate < endDate){
if (startdate.getDay() === 0){
epiphanyUS = startdate;
}
startDate.setDate(startDate.getDate() + 1);
}
console.log("Epiphany is" + epiphanyUS.format("MM-DD-YYYY"));
答案 0 :(得分:2)
我修复了你的几个拼写错误并明确定义了所有变量。我认为你的while循环逻辑也可以更清晰。我不知道你是否在使用外部JS库(时刻?),但.format并不是我熟悉的方法。最后,我添加了一个年变量,因此您可以快速修改它以在任何其他年份找到顿悟。
var year = 2018;
var startDate = new Date(year,0,2);
var endDate = new Date(year,0,8);
var epiphanyUS;
while (startDate <= endDate) {
if (startDate.getDay() === 0) {
epiphanyUS = startDate;
break;
} else {
startDate.setDate(startDate.getDate() + 1);
}
}
console.log("Epiphany is " + epiphanyUS.toDateString());
&#13;
答案 1 :(得分:2)
如果您更喜欢使用return语句,也可以将逻辑包装在函数中。
var startDate = new Date(2018,0,2);
var endDate = new Date(2018,0,8);
function getEpiphanyUS (startDate, endDate) {
while (startDate <= endDate) {
if (startDate.getDay() === 0){
return startDate
}
startDate.setDate(startDate.getDate() + 1);
}
}
var epiphanyUS = getEpiphanyUS (startDate, endDate)
console.log("Epiphany is " + epiphanyUS.toDateString());
&#13;
答案 2 :(得分:1)
找到匹配项时应使用break
。它可以让你走出循环。
var startDate = new Date(2018,0,2);
var endDate = new Date(2018,0,8);
var epiphanyUS; // you should also define the variable you intend to use later.
while (startDate <= endDate){ // inclusive of endDate
if (startDate.getDay() === 0){
epiphanyUS = startDate; // fix the typo. It's startDate, not startdate
break; // break when match is found.
}
startDate.setDate(startDate.getDate() + 1);
}
// check for presence and do stuff accordingly, like console.log
if(epiphanyUS) console.log("Epiphany is " + epiphanyUS);
答案 3 :(得分:1)
var startDate = new Date(2018,0,2);
var endDate = new Date(2018,0,8);
var epiphanyUS;
while (startDate < endDate){
if (startDate.getDay() === 0){
epiphanyUS = startDate;
}
startDate.setDate(startDate.getDate() + 1);
}
function format(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return month + '/' + day + '/' + year;
}
console.log("Epiphany is " + format(epiphanyUS));
&#13;
注意像startDate和startdate这样的大写拼写错误。
答案 4 :(得分:1)
如果您减少逻辑以在特定年份的1月2日或之后返回第一个星期日,则可以大大简化代码:
/* @param {number} year - year to get epiphany for. Defaults to current year
** @returns {Date} First Sunday on or after 2 January for given year
*/
function getEpiphanyUS(year = new Date().getFullYear()) {
var d = new Date(year, 0, 2);
d.setDate(d.getDate() + ((7 - d.getDay()) % 7));
return d;
}
// Test 2018 + next 9 years
for (var i=0; i<10; i++) {
console.log(getEpiphanyUS(2018 + i).toString());
}
&#13;