日期计算器:两个日期之间的天数、工作日计算

介绍日期计算的方法和工具,支持天数、工作日、周数等多种计算方式。

实用工具 2026-06-08 6 分钟

日期计算器:两个日期之间的天数、工作日计算

日期计算是生活和工作中的常见需求。本文介绍日期计算的方法和工具。

日期差计算

JavaScript

function daysBetween(date1, date2) {
  const d1 = new Date(date1);
  const d2 = new Date(date2);
  const diff = Math.abs(d2 - d1);
  return Math.floor(diff / (1000 * 60 * 60 * 24));
}

// 示例
daysBetween('2024-01-01', '2024-12-31'); // 365

Java

LocalDate start = LocalDate.of(2024, 1, 1);
LocalDate end = LocalDate.of(2024, 12, 31);

long days = ChronoUnit.DAYS.between(start, end); // 365

工作日计算

function workingDaysBetween(startDate, endDate) {
  let count = 0;
  const current = new Date(startDate);
  const end = new Date(endDate);
  
  while (current <= end) {
    const day = current.getDay();
    if (day !== 0 && day !== 6) {
      count++;
    }
    current.setDate(current.getDate() + 1);
  }
  
  return count;
}

日期加减

JavaScript

const date = new Date('2024-01-01');

// 加 7 天
date.setDate(date.getDate() + 7);

// 加 1 个月
date.setMonth(date.getMonth() + 1);

// 加 1 年
date.setFullYear(date.getFullYear() + 1);

Java

LocalDate date = LocalDate.of(2024, 1, 1);

// 加 7 天
LocalDate nextWeek = date.plusDays(7);

// 加 1 个月
LocalDate nextMonth = date.plusMonths(1);

// 减 1 年
LocalDate lastYear = date.minusYears(1);

常见计算场景

1. 年龄计算

function calculateAge(birthday) {
  const birth = new Date(birthday);
  const today = new Date();
  let age = today.getFullYear() - birth.getFullYear();
  const monthDiff = today.getMonth() - birth.getMonth();
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  
  return age;
}

2. 周数计算

function weekNumber(date) {
  const d = new Date(date);
  d.setHours(0, 0, 0, 0);
  d.setDate(d.getDate() + 3 - (d.getDay() + 6) % 7);
  const week = new Date(d.getFullYear(), 0, 4);
  return 1 + Math.round(((d - week) / 86400000 - 3 + (week.getDay() + 6) % 7) / 7);
}

3. 季度计算

function quarter(date) {
  return Math.ceil((new Date(date).getMonth() + 1) / 3);
}

在线工具

使用 jsjson.com 日期计算器

  • 日期差计算
  • 工作日计算
  • 日期加减
  • 年龄计算

总结

日期计算在项目管理、财务计算、人力资源等场景中应用广泛。使用合适的工具,可以快速准确地完成日期计算。

📚 相关文章