Date对象的用法
1. Date对象的创建
写法一:表示的是当前代码执行的时间(也可以理解成是获取当前时间对象)
var date1 = new Date();
console.log(date1);
写法二:在参数中传递一个表示时间的字符串(兼容性最强)
var date2 = new Date("2023/02/14 09:00:00");
console.log(date2);
写法三:(不常用)
var date3 = new Date("Mon May 01 2023 12:00:00 GMT+0800 (中国标准时间)");
console.log(date3);
写法四:(不常用)
var date4 = new Date(2023, 10, 1); //写法四
console.log(date4);
以上四种写法的打印结果是:
2. 获取日期和时间
Date 对象 有如下方法,可以获取日期和时间:
getDate()
获取日 1-31getDay()
获取星期 0-6(0 代表周日,1 代表周一)getMonth()
获取月 0-11(0 代表一月)getFullYear()
获取年份getHours()
获取小时 0-23getMinutes()
获取分钟 0-59getSeconds()
获取秒 0-59getMilliseconds()
获取毫秒 (1s = 1000ms)
代码举例:
// 我在执行这行代码时,当前时间为 2019年2月4日,周一,13:23:52
var myDate = new Date();
console.log(myDate); // 打印结果:Mon Feb 04 2019 13:23:52 GMT+0800 (中国标准时间)
console.log(myDate.getDate()); // 打印结果:4
console.log(myDate.getDay()); // 打印结果:1
console.log(myDate.getMonth()); // 打印结果:1
console.log(myDate.getFullYear()); // 打印结果:2019
console.log(myDate.getHours()); // 打印结果:13
console.log(myDate.getMinutes()); // 打印结果:23
console.log(myDate.getSeconds()); // 打印结果:52
console.log(myDate.getMilliseconds()); // 打印结果:393
console.log(myDate.getTime()); // 获取时间戳。打印结果:1549257832393
3. getTime():获取时间戳
Date 对象 还有如下方法:
getTime()
获取当前日期对象的时间戳。这个方法在实际开发中,用得比较多。
啥叫时间戳?接下来,我们解释一下。
时间戳:指的是从格林威治标准时间的1970年1月1日,0时0分0秒
到当前日期所花费的毫秒数(1 秒 = 1000 毫秒)。
计算机底层在保存时间时,使用的都是时间戳。时间戳的存在,就是为了统一时间的单位。
利用时间戳检测代码的执行时间:
我们可以在业务代码的前面定义 时间戳1
,在业务代码的后面定义 时间戳2
。把这两个时间戳相减,就能得出业务代码的执行时间。
文档更新时间: 2023-01-10 11:17 作者:孙老师