JS原生时间使用
let date = new Date();
console.log(date.getFullYear()); //当前日期的年 2022
console.log(date.getMonth() + 1); //月份+1 由于月份是0-11计算 所以需要 +1
console.log(date.getDate()); // 日
console.log(date.getDay()); // 星期几 注意:星期日返回的是0
console.log(date.getHours()); // 时
console.log(date.getMinutes()); // 分
console.log(date.getSeconds()); // 秒
//获取时间戳
// 写法一
console.log(date.valueOf()); //现在时间距离1970.1.1的毫秒数
console.log(date.getTime());
// 写法二
let date = +new Date();
console.log(date); //返回当前总的毫秒数
// 写法三
console.log(Date.now()); // H5新增 低版本浏览器打不开
//封装倒计时
function countDown(time) {
let dateNow = +new Date(); // 获取当前时间的毫秒数
let dateOver = +new Date(time); // 获取目标时间的毫秒数
let gapTime = (dateOver - dateNow) / 1000 // 由毫秒得到秒
let s = pad(parseInt(gapTime % 60)); // 秒数
let m = pad(parseInt(gapTime / 60 % 60)); // 分钟数
let h = pad(parseInt(gapTime / 60 / 60 % 24)); // 小时数
let d = pad(parseInt(cha / 60 / 60 / 24)); // 天数
return d + '天' + h + '小时' + m + '分钟' + s + '秒';
}
// 时间标准的处理函数
function pad(timeEl, total = 2, str = '0') {
return timeEl.toString().padStart(total, str)
}
// 调用函数
console.log(countDown('2122-5-19 8:00:00'));
moment.js使用
moment(时间戳).format('YYYY-MM-DD HH:mm:ss')
//YYYY 年份 MM 月份 DD 天数 HH 24小时 hh 12小时 MM 分钟 ss 秒数
//W 一年中的第几周 d 星期几 Q季度 X10位的时间戳
moment(new Date()).valueOf() //获取当前时间戳
moment().year() //获取年份
moment().month() //获取月份 需要加1
moment().day() //获取天数
//当前时间七天前
moment(new Date()).subtract('days',7).format('YYYY年MM月DD日'); //2014年10月01日
//当前时间七天后
moment(new Date()).add('days',7).format('YYYY年MM月DD日'); //2014年10月01日
//当前时间9小时前
moment(new Date()).subtract('hours',9).format('HH:mm:ss');
//当前时间9小时后
moment(new Date()).add('hours',9).format('YYYY年MM月DD日');