JavaScript时间计算函数封装
在日常开发中,处理时间和日期是 JavaScript 中非常常见的需求。无论是计算两个日期之间的差值、格式化日期时间,还是获取某个月的天数,这些操作都需要我们编写大量的代码。为了简化开发流程并提高代码的可维护性,我们可以将这些常用的时间计算功能封装成函数。
本文将分享一些常用的 JavaScript 时间计算函数,并提供使用示例,帮助你更高效地处理时间和日期。
格式化日期时间
function formatDateTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
const pad = (num) => num.toString().padStart(2, '0');
return format
.replace('YYYY', date.getFullYear())
.replace('MM', pad(date.getMonth() + 1))
.replace('DD', pad(date.getDate()))
.replace('HH', pad(date.getHours()))
.replace('mm', pad(date.getMinutes()))
.replace('ss', pad(date.getSeconds()));
}
计算两个日期之间的天数差
function getDaysBetweenDates(date1, date2 = new Date()) {
const timeDiff = Math.abs(new Date(date2).getTime() - new Date(date1).getTime());
return Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
}
添加天数到指定日期
function addDays(days, date=new Date()) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
计算两个日期之间的小时差
function getHoursBetweenDates(date1, date2=new Date()) {
const timeDiff = Math.abs(new Date(date2).getTime() - new Date(date1).getTime());
return Math.ceil(timeDiff / (1000 * 60 * 60));
}
判断是否为闰年
function isLeapYear(year = new Date().getFullYear()) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
获取某个月的天数
function getDaysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
计算年龄
function calculateAge(birthDate) {
const today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
调用示例
console.log('Current DateTime:', formatDateTime());
const futureDate = addDays(10);
console.log('Future Date:', formatDateTime(futureDate));
const daysDiff = getDaysBetweenDates(futureDate);
console.log('Days Difference:', daysDiff);
console.log('Is Leap Year 2024:', isLeapYear(2024));
console.log('Days in February 2023:', getDaysInMonth(2024, 1));
const birthDate = new Date(2000, 5, 15);
console.log('Age:', calculateAge(birthDate));
输出
Current DateTime: 2025-03-05 14:42:23
Future Date: 2025-03-15 14:42:23
Days Difference: 10
Is Leap Year 2024: true
Days in February 2023: 29
Age: 24
通过封装这些常用的时间计算函数,我们可以大大简化 JavaScript 中的日期和时间处理逻辑。这些函数不仅提高了代码的可读性和可维护性,还能减少重复代码的编写。希望这些函数能为你的开发工作带来便利!
如果你有其他常用的时间处理需求,欢迎在评论区分享,我们一起完善这个工具库!