javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS日期处理

JavaScript常用的日期时间函数封装及其详细说明

作者:~无忧花开~

在Web开发中,日期格式化是常见需求,下面这篇文章主要介绍了JavaScript常用的日期时间函数封装及其详细说明的相关资料,文中通过代码介绍非常详细,需要的朋友可以参考下

JavaScript 日期时间函数封装

JavaScript 提供了丰富的日期时间处理函数,但直接使用原生 API 可能不够便捷。通过封装常用函数,可以提高代码复用性和可读性。以下是一些常用的日期时间函数封装及其详细说明。

获取当前时间戳

封装一个函数获取当前时间戳,可以是毫秒级或秒级。

function getTimestamp(unit = 'ms') {
  const timestamp = Date.now();
  return unit === 's' ? Math.floor(timestamp / 1000) : timestamp;
}

格式化日期

将日期对象格式化为指定的字符串形式,例如 YYYY-MM-DD HH:mm:ss

function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
}

解析日期字符串

将日期字符串解析为 Date 对象,支持多种常见格式。

function parseDate(dateString) {
  if (!dateString) return new Date();
  if (dateString instanceof Date) return dateString;
  if (typeof dateString === 'number') return new Date(dateString);

  const patterns = [
    /^(\d{4})-(\d{2})-(\d{2})$/, // YYYY-MM-DD
    /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/, // YYYY-MM-DD HH:mm:ss
    /^(\d{4})\/(\d{2})\/(\d{2})$/, // YYYY/MM/DD
  ];

  for (const pattern of patterns) {
    const match = dateString.match(pattern);
    if (match) {
      const [, year, month, day, hours = 0, minutes = 0, seconds = 0] = match;
      return new Date(year, month - 1, day, hours, minutes, seconds);
    }
  }

  return new Date(dateString); // Fallback to native parsing
}

计算日期差

计算两个日期之间的差值,返回天、小时、分钟或秒。

function dateDiff(startDate, endDate, unit = 'day') {
  const diffMs = endDate - startDate;
  const units = {
    day: 1000 * 60 * 60 * 24,
    hour: 1000 * 60 * 60,
    minute: 1000 * 60,
    second: 1000,
  };

  return Math.floor(diffMs / units[unit]);
}

日期加减

对日期进行加减操作,支持年、月、日等单位。

function dateAdd(date, amount, unit = 'day') {
  const result = new Date(date);
  const units = {
    year: 'FullYear',
    month: 'Month',
    day: 'Date',
    hour: 'Hours',
    minute: 'Minutes',
    second: 'Seconds',
  };

  if (units[unit]) {
    result[`set${units[unit]}`](result[`get${units[unit]}`]() + amount);
  }
  return result;
}

获取月份的天数

获取指定年份和月份的天数。

function getDaysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}

判断是否为闰年

判断指定年份是否为闰年。

function isLeapYear(year) {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}

获取季度

根据月份获取所在的季度。

function getQuarter(month) {
  return Math.floor(month / 3) + 1;
}

时间戳转日期

将时间戳转换为 Date 对象。

function timestampToDate(timestamp) {
  return new Date(timestamp);
}

日期转时间戳

Date 对象或日期字符串转换为时间戳。

function dateToTimestamp(date, unit = 'ms') {
  const timestamp = date instanceof Date ? date.getTime() : new Date(date).getTime();
  return unit === 's' ? Math.floor(timestamp / 1000) : timestamp;
}

判断日期是否相等

比较两个日期是否相等,支持精确到天、小时或分钟。

function isSameDate(date1, date2, unit = 'day') {
  const d1 = new Date(date1);
  const d2 = new Date(date2);
  const units = {
    year: 'FullYear',
    month: 'Month',
    day: 'Date',
    hour: 'Hours',
    minute: 'Minutes',
  };

  if (units[unit]) {
    return d1[`get${units[unit]}`]() === d2[`get${units[unit]}`]();
  }
  return d1.getTime() === d2.getTime();
}

获取当前时间的零点

获取当前日期的零点时间(00:00:00)。

function getStartOfDay(date) {
  const d = new Date(date);
  d.setHours(0, 0, 0, 0);
  return d;
}

获取当前时间的结束时间

获取当前日期的结束时间(23:59:59)。

function getEndOfDay(date) {
  const d = new Date(date);
  d.setHours(23, 59, 59, 999);
  return d;
}

判断日期是否在范围内

判断一个日期是否在指定的日期范围内。

function isDateInRange(date, startDate, endDate) {
  const d = new Date(date);
  const start = new Date(startDate);
  const end = new Date(endDate);
  return d >= start && d <= end;
}

获取星期几

获取指定日期是星期几,返回数字或名称。

function getDayOfWeek(date, format = 'number') {
  const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  const day = new Date(date).getDay();
  return format === 'name' ? days[day] : day;
}

获取时间段的月份列表

获取两个日期之间的所有月份。

function getMonthsBetweenDates(startDate, endDate) {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const months = [];
  let current = new Date(start);

  while (current <= end) {
    months.push(new Date(current));
    current.setMonth(current.getMonth() + 1);
  }

  return months;
}

时区转换

将日期从一个时区转换到另一个时区。

function convertTimeZone(date, targetTimeZone) {
  const options = { timeZone: targetTimeZone };
  return new Date(date.toLocaleString('en-US', options));
}

日期有效性检查

检查一个日期是否有效。

function isValidDate(date) {
  return date instanceof Date && !isNaN(date.getTime());
}

总结

以上封装涵盖了 JavaScript 日期时间处理的常见需求,包括格式化、解析、计算、比较和时区转换等。通过合理封装,可以减少重复代码,提高开发效率。实际使用时,可以根据项目需求进一步调整或扩展这些函数。

您可能感兴趣的文章:
阅读全文