JS内置对象Date() (学习整理)

tech2022-07-07  211

let now = new Date() console.log(now);//打印当前日期 console.log(now.getFullYear());//打印年 console.log(now.getMonth() + 1);//打印月(月份要+1) console.log(now.getDate());//打印日 console.log(now.getHours());//打印小时 console.log(now.getMinutes());//打印分钟 console.log(now.getSeconds());//打印秒钟

打印例如“2020-09-02 15:23:36”的日期(此例子打印的是当前网络时间)

let ymd = ([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-')); let hms = ([now.getHours(), now.getMinutes(), now.getSeconds()].join(':')); let all = [ymd, hms].join(' ') console.log(ymd); console.log(hms); console.log(all);

打印今天是星期几

console.log(now.getDay()); //获取星期0-6 let str = '星期' + '日一二三四五六' [now.getDay()] //输出今天是星期几 console.log(str);

微信朋友圈动态发布时间demo

let d3 = new Date() let d4 = new Date('2020-08-31 16:24:22') let ymd = [d4.getFullYear(), d4.getMonth() + 1, d4.getDate()].join('-'); let hms = [d4.getHours(), d4.getMinutes(), d4.getSeconds()].join(':'); let sec = (d3 - d4) / 1000 //毫秒变成秒 if (sec < 60) { console.log('刚刚'); } else if (sec < 60 * 60) { console.log(Math.floor(sec / 60) + '分钟前'); } else if (sec < 60 * 60 * 24) { console.log(Math.floor(sec / 60 / 60) + '小时前'); } else { console.log(`${ymd} ${hms}`); }

定时器

//定时器 setInterval(function () { let ymd = ([now.getFullYear(), now.getMonth() + 1,now.getDate()].join('-')); let hms = ([now.getHours(), now.getMinutes(), now.getSeconds()].join(':')); let all = [ymd, hms].join(' ') console.log(all); }, 1000)

倒计时demo

// 倒计时 let time = new Date() let six = new Date('2020-08-31 18:00:00') let sec = (six - time) / 1000 let hour = (Math.floor(sec / 3600)); let minute = (Math.floor(sec % 3600 / 60)); let second = (Math.floor(sec % 3600 % 60)); hour = hour < 10 ? ('0' + hour) : hour minute = minute < 10 ? ('0' + minute) : minute second = second < 10 ? ('0' + second) : second console.log([hour, minute, second].join(':'));
最新回复(0)