使用JavaScript实现时间格式化与计算_javascript工具函数

答案:封装时间格式化与相对时间计算函数可提升开发效率。通过formatTime将日期转为“YYYY-MM-DD HH:mm:ss”等格式,支持自定义输出;利用timeAgo计算时间差,返回“刚刚”“3分钟前”等人性化提示,增强用户体验。

在日常开发中,时间的格式化与计算是常见的需求。JavaScript 提供了原生的 Date 对象,但其默认输出不够友好,且缺少一些便捷操作。通过封装工具函数,我们可以更高效地处理时间相关的逻辑。

时间格式化:将日期转为可读字符串

很多时候需要将 Date 对象转换成“YYYY-MM-DD HH:mm:ss”这样的格式。可以写一个通用的格式化函数:

function formatTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
  const d = date instanceof Date ? date : new Date(date);
  if (isNaN(d.getTime())) throw new Error('Invalid Date');

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hour = String(d.getHours()).padStart(2, '0');
  const minute = String(d.getMinutes()).padStart(2, '0');
  const second = String(d.getSeconds()).padStart(2, '0');

  return format
    .replace(/YYYY/g, year)
    .replace(/MM/g, month)
    .replace(/DD/g, day)
    .replace(/HH/g, hour)
    .replace(/mm/g, minute)
    .replace(/ss/g, second);
}

使用示例:

// formatTime(new Date()) → "2025-04-05 14:30:22"
// formatTime(Date.now(), 'YYYY/MM/DD') → "2025/04/05"

时间差计算:获取两个时间之间的间隔

常用于显示“刚刚”、“3分钟前”、“昨天”等相对时间描述,或精确计算天数、小时等。

function timeAgo(timestamp) {
  const now = Date.now();
  const diff = Math.floor((now - new Date(timestamp)) / 1000);

  if (diff
  if (diff
  if (diff
  if (diff
  return `${Math.floor(diff / 86400)}天前`;
}

如果需要精确的时间差对象,可用:

function diffTime(start, end) {
  const startTime = new Date(start).getTime();
  const endTime = new Date(end).getTime();
  const diffMs = Math.abs(endTime - startTime);

  const seconds = Math.floor(diffMs / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  return { days, hours: hours % 24, minutes: minutes % 60, seconds: seconds % 60 };
}

常用时间快捷获取

项目中经常需要获取“今天零点”、“本周一”、“本月第一天”等特殊时间点,可以封装辅助函数:

// 获取当天 00:00:00 的时间戳
function getTodayStart() {
  const now = new Date();
  return new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
}

// 获取本月第一天
function getMonthFirstDay() {
  const now = new Date();
  return new Date(now.getFullYear(), now.getMonth(), 1).getTime();
}

// 获取本周一 00:00:00
function getMondayOfThisWeek() {
  const now = new Date();
  const day = now.getDay() || 7; // 周日返回0,转为7
  const diff = now.getDate() - day + 1;
  return new Date(now.setDate(diff)).setHours(0, 0, 0, 0);
}

这些函数在做数据统计、筛选条件时非常实用。

基本上就这些,你可以根据项目需要扩展更多功能,比如支持时区、国际化格式等。核心思路是:封装重复逻辑,提升代码可读性和复用性。