Date对象常用方法
本文最后更新于:2 年前
Date对象常用方法
获取 Date 对象的时间戳
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <script> const timestamp1 = +new Date(); console.log(timestamp1);
const timestamp2 = new Date().getTime(); console.log(timestamp2);
const timestamp3 = new Date().valueOf(); console.log(timestamp3);
const timestamp4 = new Date() * 1; console.log(timestamp4);
const timestamp5 = Number(new Date()); console.log(timestamp5); </script>
|
日期格式化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <script> console.log(formatDate());
function formatDate() {
var date = new Date();
var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate();
var week = date.getDay(); var weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var hour = date.getHours(); hour = hour < 10 ? '0' + hour : hour;
var minute = date.getMinutes(); minute = minute < 10 ? '0' + minute : minute;
var second = date.getSeconds(); second = second < 10 ? '0' + second : second;
var result = '今天是:' + year + '年' + month + '月' + day + '日 ' + hour + ':' + minute + ':' + second + ' ' + weekArr[week];
return result; } </script>
|
倒计时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <style> div { width: 1210px; margin: 200px auto; color: red; text-align: center; font: 600 30px/30px 'simsun'; } </style> </head> <body> <div></div>
<script> var div = document.getElementsByTagName('div')[0];
var timer = setInterval(() => { countDown('2032/02/03 11:20:00'); }, 1);
function countDown(myTime) { var nowTime = new Date(); var future = new Date(myTime); var timeSum = future.getTime() - nowTime.getTime();
var day = parseInt(timeSum / 1000 / 60 / 60 / 24); var hour = parseInt((timeSum / 1000 / 60 / 60) % 24); var minu = parseInt((timeSum / 1000 / 60) % 60); var sec = parseInt((timeSum / 1000) % 60); var millsec = parseInt(timeSum % 1000);
day = day < 10 ? '0' + day : day; hour = hour < 10 ? '0' + hour : hour; minu = minu < 10 ? '0' + minu : minu; sec = sec < 10 ? '0' + sec : sec; if (millsec < 10) { millsec = '00' + millsec; } else if (millsec < 100) { millsec = '0' + millsec; }
if (timeSum < 0) { div.innerHTML = '距离2032/02/03 11:20:00还有00天00小时00分00秒000毫秒'; clearInterval(timer); return; }
div.innerHTML = '距离2032/02/03 11:20:00还有' + day + '天' + hour + '小时' + minu + '分' + sec + '秒' + millsec + '毫秒'; } </script> </body>
|