携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第22天,点击查看活动详情
内置对象Date的常见方法
Date对象通常用来处理时间,在开发中用得很多,是一个构造函数,但是Date和Math对象不一样,Date对象需要实例化后才能使用。
如何创建Date对象
在创建Date对象时,一般用关键字new进行创建,创建的对象分为传递参数和不传递参数两类,如:
不传递参数(默认获取当前的时间):
var time1 = new Date();
console.log(time1);//Wed Aug 17 2022 00:14:06 GMT+0800 (中国标准时间)
传递参数(字符串/数字/时间戳):
字符串:
var time2 = new Date('2022/08/17 12:00:00';
console.log(time2);//Wed Aug 17 2022 12:00:00 GMT+0800 (中国标准时间)
数字:
var time3 = new Date(2022, 8, 17, 12, 00, 00);
console.log(time3);//Sat Sep 17 2022 12:00:00 GMT+0800 (中国标准时间)
可能有人会问,为什么我输入的是8月,打印出来的却是Sep九月,其实这是js语言标准,只要记住这条规则就行。
时间戳:
var time4 = new Date(2022817120000);
console.log(time4);//Mon Feb 06 2034 13:38:40 GMT+0800 (中国标准时间)
这里大家要注意的是,时间戳并不是真正的日期时间,而是一种表示日期时间的方式,通常我们是将后端传来的时间戳通过这种方法转换为我们能够看懂的日期。
获取日期指定部分
方法:
| 方法 | 解释说明 |
|---|---|
| getFullYear() | 获取年份 |
| getMonth() | 获取月份(0~11)(0表示1月,以此类推) |
| getDate() | 获取日(1~31) |
| getDay() | 获取星期(0~6)(0表示周日,其他正常) |
| getHours() | 获取小时(0~23) |
| getMinutes() | 获取分钟(0~59) |
| getSeconds() | 获取秒(0~59) |
| getMilliseconds() | 获取毫秒 |
例如:
var time5 = new Date();//获取当前系统时间
console.log(time5);
console.log(time5.getFullYear());
console.log(time5.getMonth());
console.log(time5.getDate());
console.log(time5.getDay());
console.log(time5.getHours());
console.log(time5.getMinutes());
console.log(time5.getSeconds());
console.log(time5.getMilliseconds());
打印结果: