new Date() 获取当前时间对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>温故而知“心”</title>
<style></style>
</head>
<body></body>
<script>
let time = new Date();
console.log("获取当前时间的年份 本地时间:", time.getFullYear())
console.log("获取当前时间的月份 (0-11):", time.getMonth())
console.log("获取当前时间的日 (1-31) 这个月中的第几天:", time.getDate())
console.log("获取当前时间的小时数 (1-24):", time.getHours())
console.log("获取当前时间的分钟数 (0-59):", time.getMinutes())
console.log("获取当前时间的秒钟数 (0-59):", time.getSeconds())
console.log("获取当前时间在一个星期中是第几天:", time.getDay())
console.log(" 获取当前时间的时间戳:", time.getTime())
console.log( new Date("2020-3-23 16:59:07") )
console.log( new Date("Mar 23,2020") )
console.log( new Date("2020/03/23") )
</script>
</html>
getTime:返回1970年1月1日到至今的毫秒数,常用于时间戳。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
</body>
<script>
let firstTime = new Date().getTime();
for (let i = 0; i < 100000000; i++) {
}
let lastTime = new Date().getTime();
console.log(lastTime - firstTime);
</script>
</html>
封装函数,打印当前是何年何月何日何时,几分几秒。(注意封装的方法最好通过原型来写)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
</body>
<script>
Date.prototype.getCurrentTime = function () {
let date = new Date();
const year = date.getFullYear();
const month = date.getMonth()+1;
const dates = date.getDate();
const hours = date.getHours();
const minute = date.getMinutes();
const seconds = date.getSeconds();
return `${year}年${month}月${dates}日${hours}时${minute}分${seconds}秒`;
};
const date = new Date();
console.log(date.getCurrentTime());
</script>
</html>