Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 检查闰年的程序

检查闰年的 JavaScript 程序

在这个例子中,你将学习编写一个 JavaScript 程序来检查一年是否是闰年。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 日期和时间 JavaScript if...else 语句
满足以下条件的年份为闰年:
年份是 400 的倍数。 年份是4的倍数,而不是100的倍数。

示例 1: 使用 if...else 检查闰年

// program to check leap year
function checkLeapYear(year) {
    //three conditions to find out the leap year
    if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {
        console.log(year + ' is a leap year');
    } else {
        console.log(year + ' is not a leap year');
    }
}
// take input
const year = prompt('Enter a year:');
checkLeapYear(year);
输出
Enter a year: 2000
2000 is a leap year
在上面的程序中,通过检查三个条件来确定年份是否为闰年。
% 运算符返回除法的余数。

示例 2: 使用 newDate() 检查闰年

// program to check leap year
function checkLeapYear(year) {
    const leap = new Date(year, 1, 29).getDate() === 29;
    if (leap) {
        console.log(year + ' is a leap year');
    } else {
        console.log(year + ' is not a leap year');
    }
}
// take input
const year = prompt('Enter a year:');
checkLeapYear(year);
输出
Enter a year: 2000
2000 is a leap year
在上述程序中,检查二月是否包含29天。
如果 2 月份包含 29 天,则为闰年。
new Date(2000, 1, 29) 根据指定的参数给出日期和时间。
Tue Feb 29 2000 00:00:00 GMT+0545 (+0545)
getDate() 方法返回一个月中的哪一天。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4