获取本地时间
let date = new Date()
console.log(date)
// 输出结果 VM11397:1 Tue Jun 21 2022 14:48:30 GMT+0800 (中国标准时间)
时间格式化: 例如时间有 2022-06-13 提取月份 和日期
let date = new Date('2022-06-13')
console.log(date.getMonth()) //输出结果是 5
let month = date.getMonth()+1
console.log(month) // 输出结果 6
let mydate = date.getDate() // 获取日
console.log(mydate) // 输出结果 13
let day = mo.getDay()
console.log(day) // 输出结果是 星期一
控制台调试结果
还可以使用截取子串的方法 substring()
// 2022-06-13 获取字符串中的
let string = '2022-06-13'
let month = string.substring(5,7)
console.log(month) // 06
获取前一天日期
// this.mytime 是 当前日期 例如 '2022-07-13'
let now = new Date().getHours(); // 获取当前小时 24小时制
console.log(now,'当前日期')
if(now>9){
let beforeDay = new Date(new Date(this.mytime).getTime() - 24 * 60 * 60 * 1000 ); // 获取前一天日期
this.mytime = moment(beforeDay).format('YYYY-MM-DD')
}
}
javascript 实现获取当前时间的日期
计算当前月的天数
getCountsDate(){
// 获取当前时间
let date =new Date();
// 获取当前的月份
let curMonth = date.getMonth();
// 将月份设置为下一个月
date.setMonth(curMonth+1);
// 将日期设置为O 就会自动计算下一个月的最后一天的日期
date.setDate(0);
console.log(`date.getDate`, date.getDate()); //得到当前月的天数
return date.getDate();
}
// 调用获取
demo(){
let counts = this.getCountsDate()
console.log(counts)
}