本文介绍了javascript 查找闰年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个月的二月时,如何让下面的代码工作?目前它正在进入这一天,然后在进入 if 之前停止以确定它是否是闰年.

How can I get the code below to work when I have a month of february? Currently it is getting to the day and then stopping before getting to the if to determine whether it is a leap year.

 if (month == 2) {
    if (day == 29) {
        if (year % 4 != 0 || year % 100 == 0 && year % 400 != 0) {
            field.focus();
             field.value = month +'/' +  '';
        }
    }
    else if (day > 28) {
        field.focus();
             field.value = month +'/' +  '';
    }
}

推荐答案

使用日期对象 用于日期时间的东西,例如

It's safer to use Date objects for datetime stuff, e.g.

isLeap = new Date(year, 1, 29).getMonth() == 1

由于人们一直在问这到底是如何工作的,这与 JS 如何从年-月-日计算日期值有关(详细信息 此处).基本上,它首先计算当月的第一天,然后添加 N -1 天.因此,当我们要求非闰年的 2 月 29 日时,结果将是 2 月 1 日 + 28 天 = 3 月 1 日:

Since people keep asking about how exactly this works, it has to do with how JS calculates the date value from year-month-day (details here). Basically, it first calculates the first of the month and then adds N -1 days to it. So when we're asking for the 29th Feb on a non-leap year, the result will be the 1st Feb + 28 days = 1st March:

> new Date(2015, 1, 29)
< Sun Mar 01 2015 00:00:00 GMT+0100 (CET)

在闰年,1 日 + 28 = 2 月 29 日:

On a leap year, the 1st + 28 = 29th Feb:

> new Date(2016, 1, 29)
< Mon Feb 29 2016 00:00:00 GMT+0100 (CET)

在上面的代码中,我将日期设置为 2 月 29 日,然后查看是否发生了翻转.如果不是(月份仍为1,即二月),则这是闰年,否则为非闰年.

In the code above, I set the date to 29th Feb and look if a roll-over took place. If not (the month is still 1, i.e. February), this is a leap year, otherwise a non-leap one.

这篇关于javascript 查找闰年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:56