HTML:
在输入文本字段中输入一年(例如2004)。如何使用JavaScript自动计算当年哪个星期圣诞节降临?
答案 0 :(得分:1)
var year = 2004, //year
dateObj = new Date(year, 11, 25); //Note: 11 means "December"
dateObj.getDay(); //6
//Most reliable value.
dateObj.toString().substr(0, 3); //"Sat"
//Note: Although the specification does not specify the format of the returned
// value of .toString, in most browsers, the first term should be the
// name of the day of the week. If you prefer a more "reliable" method,
// use a custom Array with day names.
dateObj.toLocaleString("en", {weekday: "long"}) //"Saturday"
//Available in new browsers.
关于强>
<强>演示强>
答案 1 :(得分:0)
如果您可以将年份输入分配给变量
var year = 2004 // Year entered into field input
然后,您可以执行以下操作以获取特定假期的星期几:
// Use this array to create day of the week names:
var dayStringArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Create date of holiday with year entered.
var xmas = new Date(year, 11, 25); // 11 is for December (i.e. 12 - 1)
// This creates a Date object of Dec 25th, 2004
// Get day of week in 0 - 6 integer, then use array to get day text.
var xmasDayString = dayStringArray[xmas.getDay()];
console.log(xmasDayString); // Outputs "Saturday"
答案 2 :(得分:0)
halfnibble非常接近,但不必要地使用字符串解析而不是离散值。
function getChristmasDayName(year) {
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var d = new Date(year, 11, 25);
d.setFullYear(year); // required to support years 0 to 99
return dayNames[d.getDay()];
}
alert(getChristmasDayName(2004)); // Saturday
以上假设英文日名称和公历。对其他语言的支持将需要该语言中的其他日期名称数组。支持其他日历需要更多工作。