📅  最后修改于: 2023-12-03 15:01:39.822000             🧑  作者: Mango
JavaScript中的日期对象用于处理日期和时间。日期对象包含日期(年月日)和时间(小时分钟秒毫秒)信息,可以进行一系列的操作,如获取当前时间、计算两个时间之间的差值等等。
通过new Date()
可以创建一个日期对象。如果不传递任何参数,则表示当前时间:
const now = new Date();
console.log(now); // 2022-10-13T17:54:57.905Z
也可以通过传递一个日期字符串或时间戳来创建日期对象:
const date1 = new Date('2021-10-01');
console.log(date1); // 2021-10-01T00:00:00.000Z
const date2 = new Date(1633075200000);
console.log(date2); // 2021-10-01T00:00:00.000Z
可以通过日期对象的各种方法获取日期的不同部分信息。
通过getFullYear()
方法获取年份:
const year = now.getFullYear();
console.log(year); // 2022
通过getMonth()
方法获取月份,返回值为0~11,需要加1才是实际的月份:
const month = now.getMonth() + 1;
console.log(month); // 10
通过getDate()
方法获取日期:
const date = now.getDate();
console.log(date); // 13
通过getDay()
方法获取星期,返回值为0~6,0表示星期日,1表示星期一,以此类推:
const day = now.getDay();
console.log(day); // 4
通过getHours()
、getMinutes()
、getSeconds()
、getMilliseconds()
方法获取小时、分钟、秒、毫秒:
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const milliseconds = now.getMilliseconds();
console.log(hours, minutes, seconds, milliseconds); // 17 54 57 905
除了获取日期信息,还可以通过一系列的方法修改日期信息。
通过setFullYear()
方法设置年份:
now.setFullYear(2023);
console.log(now); // 2023-10-13T17:54:57.905Z
通过setMonth()
方法设置月份,注意月份从0开始计数:
now.setMonth(11);
console.log(now); // 2023-12-13T17:54:57.905Z
通过setDate()
方法设置日期:
now.setDate(15);
console.log(now); // 2023-12-15T17:54:57.905Z
通过setHours()
、setMinutes()
、setSeconds()
、setMilliseconds()
方法设置小时、分钟、秒、毫秒:
now.setHours(18);
now.setMinutes(30);
now.setSeconds(0);
now.setMilliseconds(0);
console.log(now); // 2023-12-15T10:30:00.000Z
可以通过两个日期对象之间的差值计算时间差。通过两个日期对象相减,得到的是两个日期对象之间的毫秒数差值,可以根据需要将其转化为其他单位。
const date1 = new Date('2021-10-01');
const date2 = new Date('2022-10-01');
const diff = date2 - date1;
console.log(diff); // 31536000000
const days = diff / (1000 * 60 * 60 * 24);
const months = days / 30.4;
const years = months / 12;
console.log(days, months, years); // 365, 12.032894736842106, 1.0027412280701755
除了上述的方法,日期对象还有一些其他的方法:
getTime()
:获取日期的毫秒数表示toUTCString()
:将日期转化为UTC格式的字符串toDateString()
:将日期转化为字符串,只包含日期信息toTimeString()
:将日期转化为字符串,只包含时间信息JavaScript中的日期对象提供了方便的日期和时间处理功能。可以使用各种方法获取或修改日期信息,计算时间差等。在实际开发中需要灵活掌握这些方法,以便更好地处理日期相关的业务需求。