求助!为什么getTime和getDay返回值一直是2?

发布于 6 年前作者 houguiying1545 次浏览最后编辑 6 年前来自 ask

求助大佬 为什么 我的getmonth和getday的值一直是 2/2 ?如图 getTime会改变 但是getmonth和getday不改变 我在3/26 和 3/30 分别做了测试

2 回复
hujie
hujie1 楼5 年前

getDay 是星期几,今天星期二,返回2,没问题啊。

getMonth 月份是从0开始的,一月份是0.三月份就是2啊,也没问题啊

yangxiulan
yangxiulan2 楼4 年前

首先月份需要+1,所以3月的值为2;

其次获取日是getDate,而不是getDay(获取周几),所以周二的值为2.

const date = new Date()
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
let now = ([year, month, day]).map(n => n.toString()[1] ? n : `0${n}`).join("/") + " " + ([hour, minute, second]).map(n => n.toString()[1] ? n : `0${n}`).join(":")
console.log(now)