JavaScript Date(日期) 对象
今天我们重点学习JavaScript中的Date对象。

Date对象用于处理日期和时间。可以通过new关键词来定义Date对象。

获取时间
如获取当前系统时间。

1
2
var now = new Date();
console.log(now); //控制台的输出结果为Mon May 09 2022 13:48:39 GMT+0800 (中国标准时间)

也可以获取指定参数的时间。

1
2
3
4
5
6
7
8
9
10
11
//参数1:年份
//参数2:月份 (注意从0开始)
//参数3:日
//参数4:小时
//参数5:分钟
//参数6:秒
var date1 = new Date(new Date(2022,0,1,09,30,00));
console.log(date1);//控制台的输出结果为Sat Jan 01 2022 09:30:00 GMT+0800 (中国标准时间)
//参数非必填,可按需省略,不填默认为0
var date2 = new Date(2022,0,9);
console.log(date2);//控制台的输出结果为Sun Jan 09 2022 00:00:00 GMT+0800 (中国标准时间)

也可以将时间戳作为参数,转化成时间。

1
2
var date3 = new Date(1652076712317);
console.log(date3);//控制台的输出结果为Mon May 09 2022 14:11:52 GMT+0800 (中国标准时间)

当我们获取到时间之后, 可以通过其子函数获取对应的年、月、日、时、分、秒、时间戳等。

1
2
3
4
5
6
7
8
var now = new Date();
var year = now.getFullYear();//2022
var month = now.getMonth();//4 注意 4代表5月份
var day = now.getDate();//9
var hour = now.getHours(); // 14, 24小时制
var minute = now.getMinutes(); // 24
var second = now.getSeconds(); // 22
var time = now.getTime();//1652077528307 时间戳

格式化时间
当我们能够正确拿到时间之后,需要对时间进行格式化,以便更好的在界面上展示,或者使用正确的格式与后台数据进行交互。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var now = new Date();
console.log(now);//控制台的输出结果为Mon May 09 2022 14:58:53 GMT+0800 (中国标准时间)
var formatNow = formatDate(now);
console.log(formatNow);//控制台的输出结果为2022-05-09 14:58:53


function formatDate(time) {
if (time != null) {
var datetime = new Date();
datetime.setTime(time);
var year = datetime.getFullYear();
var month = (datetime.getMonth() + 1) < 10 ? "0" + (datetime.getMonth() + 1) : (datetime.getMonth() + 1);
var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
//获得正确的年月日时分秒之后,可根据界面要求进行自由组合
//如需转化成yyyy-mm-dd HH:mm:ss
return year + "-" + month + "-" + date + ' ' + hour + ':' + minute + ':' + second;
//如需转化成yyyy/mm/dd
// return year + "/" + month + "/" + date;
} else {
return "---";
}
}

文章内容和代码来源于网络JavaScript/JS关于时间函数的学习,并结合实际业务例子进入加强记忆,附快速获取当天、昨天等时间函数,如有侵权请联系站长立即删除。