我正在使用一个日期选择器,它给出了一个格式为太阳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
我做错了什么?
我正在使用一个日期选择器,它给出了一个格式为太阳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
我做错了什么?
假设你用你的变量
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
希望这能有所帮助
我怀疑这些方法由于历史原因缺乏一致性
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
是的,对于某些人来说,这似乎是一个愚蠢的决定,使月份成为零索引,而年和日不是。这里有一个小函数,我用来将日期转换为字段预期的格式…
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)}`
你也可以用这种方法找到当前月份
const today = new Date() const getMonth = (today.getMonth() + 1). tostring()。长度=== 1 ?' 0${today.getMonth() + 1} ':today.getMonth() + 1