前端写项目时, 有时会需要获取当前时间, 虽然使用度不高, 难免有需要的时候.
下面整理获取当前时间代码思路
使用 new Date() 获取 当前时间的时间戳
- getFullYear(): 时间戳转换的年份
- getMonth() + 1: 月份
- getDate(): 日期
- getHours()
- getMinutes()
- getSeconds()
根据需要获取相应的时间类型
var showTime = document.querySelector('.showTime');
const date = new Date();
const hour = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
// const year = date.getFullYear();
// const month = date.getMonth() + 1;
// const day = date.getDate();
// showTime.innerHTML = (`${year} : ${month} : ${day}`);
// showTime.innerHTML = (`${date.toLocaleString()}`); //"1995/12/17 上午3:24:00"
showTime.innerHTML = `${date.toDateString()}--${hour} : ${minutes} : ${seconds}` // "Sun Dec 17 1995"
其中含有方法快速获取固定类型的年月日时间类型
- toLocaleString(): "1995/12/17 上午3:24:00"
- toDateString(): "Sun Dec 17 1995"
获取DOM元素, 在元素中使用拼接, 通过innerHTML/innerText 写入元素, 显示在页面上
动态显示时间
使用setTimeout()定时器, 否则只是显示渲染页面的当前时间
var t = null;
//添加定时器, 开始运行
t = setTimeout(time, 1000);
function time() {//清除定时器clearTimeout(t);//获取时间, 定义要显示的类型...//设定定时器, 循环运行t = setTimeout(time, 1000);
}
完整代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>当前时间</title><style>*{margin: 0;padding: 0;background-color: #000;}.container{width: 100vw;height: calc(100vh);}.showTime{color: aqua;font-size: 100px;width: 100%;margin: auto;text-align: center;line-height: calc(100vh);}</style>
</head>
<body><div class="container"><div class="showTime"></div></div><script>var t = null;t = setTimeout(time, 1000);function time() {clearTimeout(t);var showTime = document.querySelector('.showTime');const date = new Date();const hour = date.getHours();const minutes = date.getMinutes();const seconds = date.getSeconds();showTime.innerHTML = `${date.toDateString()}--${hour} : ${minutes} : ${seconds}`t = setTimeout(time, 1000);} </script></body>
</html>
实现页面显示也可以通过document.write()直接写入在标签内部