日期对象
使用new进行实例化
- 获得当前时间
//1.得到当前时间 const time =new Date(); console.log(time); //2.得到指定时间 const date1 = new Date('2023-5-11'); console.log(date1);
- 案例:将当前时间展示在屏幕上
<style> div{ width: 300px; height: 40px; border: 1px solid #ccc; text-align: center; line-height: 40px; } </style> <div></div> <script> const div=document.querySelector("div"); function getMyDate() { const date =new Date(); console.log(date); let y=date.getFullYear(); console.log(y); let m=date.getMonth()+1; let s=date.getDate(); let h=date.getHours(); let min=date.getMinutes(); let sec=date.getSeconds(); h=h<10?'0'+h:h s=s<10?'0'+s:s min=min<10?'0'+min:min sec=sec<10?'0'+sec:sec return `今天是${y}-${m}-${s} ${h}:${min}:${sec}` } div.innerHTML=getMyDate();//页面刷新一开始显示 setInterval(function(){ div.innerHTML=getMyDate(); },1000) </script>
- 或者采用内置函数
div.innerHTML=date.toLocaleString();
- 时间戳
- 时间戳是指1970年1月1日00时00分00秒起至今的毫秒数
- 将来的时间戳-现在的时间戳=剩余的时间毫秒数
- 三种方法获取时间戳
//1.getTime() const date =new Date(); console.log(date.getTime()); //2.+new Date() console.log(new Date()); console.log(+new Date());//把字符串转化为字符型 //3.Date.now(),只能得到当前的时间戳,其他都能得到指定时间的 console.log(Date.now());