将获取的日期转换成如下格式
function t() {//封装获取当前时间
let date = new Date();
Y = date.getFullYear() + '-';
M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds();
console.log(h, m, s);
document.write(Y + M + D + h + m + s);
}
补充:
使用场景: 倒计时需要使用定时器,,,,
将来的时间戳-现在的时间戳
实现过程:1.创建基础样式html+css
2.获取对应时间的时间戳,时间戳转换为时间
3.封装函数,开启定时器
//获取时间
// let now=new Date();
//获取时间戳
let now = +new Date();
let future = +new Date('2023-8-18 18:00:00');
//剩余的时间戳 毫秒/1000=秒
let count = (future - now) / 1000
//将时间戳转换成时间
// h=parseInt(总秒数/60/60%24)
let h = parseInt(count / 60 / 60 % 24)
let f = parseInt(count / 60 % 60)
let s = parseInt(count % 60)