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>