当前位置: 首页 > article >正文

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 中的日期和时间处理逻辑。这些函数不仅提高了代码的可读性和可维护性,还能减少重复代码的编写。希望这些函数能为你的开发工作带来便利!

如果你有其他常用的时间处理需求,欢迎在评论区分享,我们一起完善这个工具库!


http://www.kler.cn/a/578559.html

相关文章:

  • 将长上下文大语言模型研究从输入转向输出
  • wordpress鼠标特效笔记+npm问题解决
  • fps项目二次总结
  • PDFMathTranslate安装使用
  • electron + vue3 + vite 主进程到渲染进程的单向通信
  • MyBatis Mapper 接口的作用,以及如何将 Mapper 接口与 SQL 映射文件关联起来
  • 祝福语【算法赛】
  • Conda常用命令汇总
  • 2020CVPR速读:SiamBAN,用于视觉跟踪的Siamese框自适应网络
  • Ubuntu工控卫士在制造企业中的应用案例
  • Python深度学习算法介绍
  • 聊一聊 Android 的消息机制
  • Aws batch task 无法拉取ECR 镜像unable to pull secrets or registry auth 问题排查
  • 开源项目介绍:Native-LLM-for-Android
  • 大模型量化技术原理总结 [吃果冻不吐果冻皮]
  • 设计模式 - 工厂模式 精准梳理精准记忆
  • E2-13.找单词(dfs)
  • 分布式ID生成方案:数据库号段、Redis与第三方开源实现
  • 10个实用IntelliJ IDEA插件
  • Linux(Centos 7.6)命令详解:vi