javascript 中的 getMonth 给出上个月

IT技术 javascript date
2021-01-26 12:42:35

我正在使用日期选择器,它以 Sun Jul 7 00:00:00 EDT 2013 格式给出日期。即使月份是 7 月,如果我执行 getMonth,它也会给我上个月。

var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
d1.getMonth());//gives 6 instead of 7

我究竟做错了什么?

6个回答

因为getmonth()从 0 开始。你可能想要d1.getMonth() + 1实现你想要的。

如果 getDate 给出 1-31,为什么有人希望它基于 0?
2021-03-13 12:42:35
我得说,将月份编号为零索引是我一段时间以来见过的最愚蠢的事情。'
2021-03-16 12:42:35
@DanielKhan 不,因为 12 月是 11,所以加 1 会正确地变成 12。getMonth() 函数不应该返回超过 11 的值。
2021-03-20 12:42:35
@LarryBud,推理可能与日期的其他部分(月份、年份、小时、分钟、秒...)相反,这些部分总是按原样用作数字,月份通常转换为文本,使用名称数组,当然是从 0 开始的。在 C 标准库中已经是这种情况,它必须有 40 多年的历史。
2021-03-22 12:42:35
很可能您将不得不这样做d1.getMonth() < 12 ? d1.getMonth() + 1 : 1- 否则 12 月将是 13,不是吗?
2021-04-08 12:42:35

getMonth()函数是基于零索引的。你需要做d1.getMonth() + 1

最近我使用了Moment.js库并且再也没有回头。试试看!

能说说你是怎么用的吗?
2021-04-03 12:42:35

假设你使用你的变量

var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");

月份需要 +1 才能准确,它从 0 开始计数

d1.getMonth() + 1 // month 

相比之下......这些方法不需要加1

d1.getSeconds()   // seconds 
d1.getMinutes()   // minutes 
d1.getDate()      // date    

并注意它.getDate()不是。getDay()

d1.getDay()       // day of the week as a 

希望这可以帮助

我怀疑这些方法由于历史原因缺乏一致性

const d = new Date();
const time = d.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second:'numeric', hour12: true });
const date = d.toLocaleString('en-US', { day: 'numeric', month: 'numeric', year:'numeric' });

或者

const full_date = new Date().toLocaleDateString(); //Date String
const full_time = new Date().toLocaleTimeString(); // Time String

输出

日期 = 8/13/2020

时间 = 12:06:13 AM

是的,这似乎是某人愚蠢的决定,将月份设为零索引,而年份和日期不是。这是我用来将日期转换为该字段预期格式的一个小函数...

const now = new Date()
const month = (date) => {
    const m = date.getMonth() + 1;
    if (m.toString().length === 1) {
        return `0${m}`;
    } else {
        return m;
    }
};
const day = (date) => {
    const d = date.getDate();
    if (d.toString().length === 1) {
        return `0${d}`;
    } else {
        return d;
    }
};

const formattedDate = `${now.getFullYear()}-${month(now)}-${day(now)}`
你好,不错的函数,但如果 Date 是 1-9,它也应该有一个零作为前缀,这意味着长度 === 1?
2021-03-30 12:42:35
@ArttuPakarinen 抱歉,我现在才看到您的回复。是的,你是对的。我会编辑。
2021-04-03 12:42:35
您不需要所有这些行,因为您可以通过简单地这样做来避免编写它 (new Date().getMonth() + 1).toString().padStart(2, 0)
2021-04-06 12:42:35