我正在使用日期选择器,它以 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
我究竟做错了什么?
我正在使用日期选择器,它以 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
我究竟做错了什么?
因为getmonth()从 0 开始。你可能想要d1.getMonth() + 1
实现你想要的。
getMonth()
函数是基于零索引的。你需要做d1.getMonth() + 1
最近我使用了Moment.js库并且再也没有回头。试试看!
var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013");
d1.getMonth() + 1 // month
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)}`