JS Date对象
介绍
在JavaScript中,Date对象是用来处理日期和时间的对象。它允许我们创建日期对象,获取和设置日期的各个部分,执行日期的运算,以及格式化日期和时间字符串。
Date对象提供了与日期和时间相关的各种方法,包括获取年、月、日、小时、分钟、秒等等的方法,以及计算两个日期间的差距、比较日期的方法等等。
创建Date对象
在JS中,我们可以通过new Date()
构造函数创建一个Date对象。
let now = new Date();
console.log(now);
运行结果:
2022-06-22T08:00:00.000Z
这样我们就创建了一个代表当前日期和时间的Date对象。
我们还可以通过给new Date()
传递一个特定的日期字符串或时间戳来创建一个指定日期和时间的Date对象。
let specificDate = new Date('2022-12-31');
console.log(specificDate);
let timestamp = Date.parse('2022-12-31T23:59:59');
let specificTime = new Date(timestamp);
console.log(specificTime);
运行结果:
2022-12-31T00:00:00.000Z
2022-12-31T23:59:59.000Z
获取日期的各个部分
Date对象提供了许多方法来获取日期的各个部分,如年、月、日、小时、分钟、秒、毫秒等。
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth(); // 返回值从 0 开始,需要注意
let date = now.getDate();
let day = now.getDay(); // 返回值为星期几,0 表示星期日
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
let millisecond = now.getMilliseconds();
console.log(year, month, date, day, hour, minute, second, millisecond);
运行结果:
2022 5 22 3 16 30 15 0
需要注意的是,getMonth()方法返回的月份是从0开始的,即0表示一月,1表示二月,依此类推。而getDay()方法返回的是星期几,0表示星期日,1表示星期一,以此类推。
设置日期的各个部分
Date对象还提供了许多方法来设置日期的各个部分,如年、月、日、小时、分钟、秒、毫秒等。
let now = new Date();
now.setFullYear(2023);
now.setMonth(11); // 11 表示十二月
now.setDate(31);
now.setHours(23);
now.setMinutes(59);
now.setSeconds(59);
now.setMilliseconds(999);
console.log(now);
运行结果:
2023-12-31T23:59:59.999Z
格式化日期和时间字符串
Date对象提供了几种方法来格式化日期和时间字符串。
let now = new Date();
let dateString = now.toDateString();
console.log(dateString);
let timeString = now.toTimeString();
console.log(timeString);
let localDateString = now.toLocaleDateString();
console.log(localDateString);
let localTimeString = now.toLocaleTimeString();
console.log(localTimeString);
let formatString = now.toLocaleString();
console.log(formatString);
运行结果:
Sat Jun 22 2022
16:30:15 GMT+00:00
6/22/2022
4:30:15 PM
6/22/2022, 4:30:15 PM
日期运算
Date对象也允许进行日期的加减运算。
let now = new Date();
let tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1);
console.log(tomorrow);
let nextWeek = new Date(now);
nextWeek.setDate(now.getDate() + 7);
console.log(nextWeek);
let lastMonth = new Date(now);
lastMonth.setMonth(now.getMonth() - 1);
console.log(lastMonth);
运行结果:
2022-06-23T08:00:00.000Z
2022-06-29T08:00:00.000Z
2022-05-22T08:00:00.000Z
可以使用getDate()
、getMonth()
等方法获取当前日期的具体值,然后进行相加或相减,再将结果传递给对应的set
方法即可进行日期的运算。
比较日期
我们可以使用Date对象的比较方法来比较两个日期的大小。
let now = new Date();
let specificDate = new Date('2022-12-31');
if (now > specificDate) {
console.log('now is after specificDate');
} else if (now < specificDate) {
console.log('now is before specificDate');
} else {
console.log('now is equal to specificDate');
}
运行结果:
now is before specificDate
总结
Date对象是JavaScript中处理日期和时间的重要对象。通过Date对象,我们可以创建日期对象、获取和设置日期的各个部分、执行日期的运算,以及格式化日期和时间字符串。同时,Date对象还提供了比较日期的方法,方便我们对日期进行比较和判断。