/*
Date对象
在JS中使用一个Date对象来表示一个时间
*/
/* 创建一个Date对象
如果直接使用构造函数创建一个Date对象,则会封装为当前代码执行的时间 */
var a = new Date();
console.log(a);
/*
创建一个指定的时间对象
需要在构造函数中传递一个表达时间的字符串作为参数
日期的格式 月份/日/年 时:分:秒
*/
var a1 = new Date("12/10/2021 12:10:45")
console.log(a1);
/*
getFullYear()
获取当前时间对象的年份
*/
var year = a.getFullYear();
console.log("year=" + year);
/*
get.getMonth()
获取当前时间对象的月份
0表示一月份
1表示二月份
...
11表示十二月份
*/
var month = a.getMonth();
console.log("month=" + (month + 1));
/*
getDate()
获取当前时间对象是几日
*/
var date = a.getDate();
console.log("date=" + date);
/*
getDay()
获取当前时间对象是周几
会返回一个0-6的值
0表示周日
1表示周天
*/
var day = a.getDay();
console.log("day=" + day);
/*
getHours()
获取当前时间对象的小时
*/
var hours = a.getHours();
console.log("hours=" + hours);
/*
getMinutes()
获取当前时间对象的分钟数
*/
var minutes = a.getMinutes();
console.log("minutes=" + minutes);
/*
getSeconds()
获取当前时间对象的秒数
*/
var seconds = a.getSeconds();
console.log("seconds=" + seconds);
/*
getMilliseconds()
获取当前时间对象的毫秒数
*/
var milliseconds = a.getMilliseconds();
console.log("milliseconds=" + milliseconds);
/*
getTime()
获取当前时间对象的时间戳
时间戳,指的是从格林威治标准时间的1970年1月1日,0时0分0秒
到当前日期所花费的毫秒数(1秒 = 1000毫秒)
计算机在底层保存的时间时使用都是时间戳
*/
var time = a.getTime();
console.log("time=" + time);
console.log(time / 1000 / 60 / 60 / 24 / 365);
// 获取一个循环所用的毫秒数
var start = Date.now();
console.log(start);
for (var i = 0; i < 100; i++) {
console.log(i);
}
var end = Date.now();
console.log("执行了:" + (end - start) + "毫秒");
JavaScript基础知识——Date对象
最新推荐文章于 2024-05-18 21:57:13 发布