new Date() 获取当前时间对象(getFullYear、getMonth、getDate、getHours、getMinutes、getSeconds、getDay、getTime)
文章目录new Date() 获取当前时间对象getTime:返回1970年1月1日到至今的毫秒数,常用于时间戳。封装函数,打印当前是何年何月何日何时,几分几秒。(注意封装的方法最好通过原型来写)new Date() 获取当前时间对象<!DOCTYPE html><html lang="en"><head><meta charset="...
·
文章目录
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>
/*
new Date() 获取当前时间对象
传递参数:
1.不传参数:返回当前的日期 + 时间 本地时间
2.传递的是数字:(这个数字代表一个时间戳) 返回时间戳对应的时间
3.传递的是字符串 (这个字符串代表的是一个时间)
格式: 年-月-日 时:分:秒
月(英文) 日,年
2020/03/23
时间相关的方法:
getFullYear() 获取当前时间的年份 本地时间
getMonth() 获取当前时间的月份 (0-11)
getDate() 获取当前时间的日 (1-31) 这个月中的第几天
getHours() 获取当前时间的小时数 (1-24)
getMinutes() 获取当前时间的分钟数 (0-59)
getSeconds() 获取当前时间的秒钟数 (0-59)
getDay() 获取当前时间在一个星期中是第几天
getTime() 获取当前时间的时间戳
时间戳指的是距离1970年1月1日8点的毫秒数
*/
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>
/*
getTime:返回1970年1月1日到至今的毫秒数,常用于时间戳。
下面这个时间差可以测试电脑的运行速度
*/
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;//获取月,注意时间是0-11,0代表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>
更多推荐
所有评论(0)