我正在使用一个日期选择器,它给出了一个格式为太阳7月7日00:00:00 EDT 2013年的日期。 即使月份是七月,如果我执行getMonth,它会给我前一个月的数据。

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

我做错了什么?


当前回答

getMonth()函数是基于零索引的。您需要执行d1.getMonth() + 1

最近我使用了Moment.js库,再也没有回头。试一试!

其他回答

你也可以用这种方法找到当前月份

const today = new Date() const getMonth = (today.getMonth() + 1). tostring()。长度=== 1 ?' 0${today.getMonth() + 1} ':today.getMonth() + 1

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' });

OR

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

输出

日期:8/13/2020

时间= 12:06:13

因为getmonth()从0开始。您可能需要d1.getMonth() + 1来实现您想要的结果。

getMonth()函数是基于零索引的。您需要执行d1.getMonth() + 1

最近我使用了Moment.js库,再也没有回头。试一试!

假设你用你的变量

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

Month需要+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 

希望这能有所帮助

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