最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript常用的日期時(shí)間函數(shù)封裝及其詳細(xì)說(shuō)明

 更新時(shí)間:2025年10月28日 10:30:43   作者:~無(wú)憂花開(kāi)~  
在Web開(kāi)發(fā)中,日期格式化是常見(jiàn)需求,下面這篇文章主要介紹了JavaScript常用的日期時(shí)間函數(shù)封裝及其詳細(xì)說(shuō)明的相關(guān)資料,文中通過(guò)代碼介紹非常詳細(xì),需要的朋友可以參考下

JavaScript 日期時(shí)間函數(shù)封裝

JavaScript 提供了豐富的日期時(shí)間處理函數(shù),但直接使用原生 API 可能不夠便捷。通過(guò)封裝常用函數(shù),可以提高代碼復(fù)用性和可讀性。以下是一些常用的日期時(shí)間函數(shù)封裝及其詳細(xì)說(shuō)明。

獲取當(dāng)前時(shí)間戳

封裝一個(gè)函數(shù)獲取當(dāng)前時(shí)間戳,可以是毫秒級(jí)或秒級(jí)。

function getTimestamp(unit = 'ms') {
  const timestamp = Date.now();
  return unit === 's' ? Math.floor(timestamp / 1000) : timestamp;
}
  • unit 參數(shù)用于指定返回的時(shí)間戳單位,默認(rèn)為毫秒('ms'),傳入 's' 則返回秒級(jí)時(shí)間戳。
  • Date.now() 返回當(dāng)前時(shí)間的毫秒數(shù),Math.floor 用于向下取整。

格式化日期

將日期對(duì)象格式化為指定的字符串形式,例如 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 參數(shù)是一個(gè) Date 對(duì)象。
  • format 參數(shù)指定輸出的格式,默認(rèn)是 YYYY-MM-DD HH:mm:ss
  • padStart 方法用于補(bǔ)零,確保月份、日期等始終是兩位數(shù)。

解析日期字符串

將日期字符串解析為 Date 對(duì)象,支持多種常見(jiàn)格式。

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
}
  • dateString 可以是 Date 對(duì)象、時(shí)間戳或字符串。
  • 函數(shù)嘗試匹配常見(jiàn)的日期格式,如 YYYY-MM-DDYYYY-MM-DD HH:mm:ss
  • 如果無(wú)法匹配任何模式,則回退到原生 Date 解析。

計(jì)算日期差

計(jì)算兩個(gè)日期之間的差值,返回天、小時(shí)、分鐘或秒。

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]);
}
  • startDateendDateDate 對(duì)象或時(shí)間戳。
  • unit 參數(shù)指定返回的單位,支持 day、hourminutesecond。
  • 函數(shù)返回兩個(gè)日期之間的整數(shù)差值。

日期加減

對(duì)日期進(jìn)行加減操作,支持年、月、日等單位。

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;
}
  • dateDate 對(duì)象或時(shí)間戳。
  • amount 是要加減的數(shù)量,可以是正數(shù)或負(fù)數(shù)。
  • unit 指定操作的單位,如 yearmonth、day 等。
  • 函數(shù)返回一個(gè)新的 Date 對(duì)象,不會(huì)修改原始日期。

獲取月份的天數(shù)

獲取指定年份和月份的天數(shù)。

function getDaysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}
  • yearmonth 是整數(shù),月份從 0 開(kāi)始(0 表示一月)。
  • 函數(shù)返回該月的天數(shù),自動(dòng)處理閏年。

判斷是否為閏年

判斷指定年份是否為閏年。

function isLeapYear(year) {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
  • year 是整數(shù)。
  • 函數(shù)返回布爾值,true 表示是閏年。

獲取季度

根據(jù)月份獲取所在的季度。

function getQuarter(month) {
  return Math.floor(month / 3) + 1;
}
  • month 是整數(shù),從 0 開(kāi)始。
  • 函數(shù)返回 1 到 4 之間的整數(shù),表示季度。

時(shí)間戳轉(zhuǎn)日期

將時(shí)間戳轉(zhuǎn)換為 Date 對(duì)象。

function timestampToDate(timestamp) {
  return new Date(timestamp);
}
  • timestamp 是毫秒級(jí)時(shí)間戳。
  • 函數(shù)返回對(duì)應(yīng)的 Date 對(duì)象。

日期轉(zhuǎn)時(shí)間戳

Date 對(duì)象或日期字符串轉(zhuǎn)換為時(shí)間戳。

function dateToTimestamp(date, unit = 'ms') {
  const timestamp = date instanceof Date ? date.getTime() : new Date(date).getTime();
  return unit === 's' ? Math.floor(timestamp / 1000) : timestamp;
}
  • date 可以是 Date 對(duì)象、時(shí)間戳或日期字符串。
  • unit 指定返回的時(shí)間戳單位,默認(rèn)為毫秒('ms'),傳入 's' 則返回秒級(jí)。

判斷日期是否相等

比較兩個(gè)日期是否相等,支持精確到天、小時(shí)或分鐘。

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();
}
  • date1date2Date 對(duì)象、時(shí)間戳或日期字符串。
  • unit 指定比較的精度,如 year、monthday 等。
  • 函數(shù)返回布爾值,表示兩個(gè)日期是否相等。

獲取當(dāng)前時(shí)間的零點(diǎn)

獲取當(dāng)前日期的零點(diǎn)時(shí)間(00:00:00)。

function getStartOfDay(date) {
  const d = new Date(date);
  d.setHours(0, 0, 0, 0);
  return d;
}
  • dateDate 對(duì)象、時(shí)間戳或日期字符串。
  • 函數(shù)返回一個(gè)新的 Date 對(duì)象,時(shí)間部分設(shè)置為零點(diǎn)。

獲取當(dāng)前時(shí)間的結(jié)束時(shí)間

獲取當(dāng)前日期的結(jié)束時(shí)間(23:59:59)。

function getEndOfDay(date) {
  const d = new Date(date);
  d.setHours(23, 59, 59, 999);
  return d;
}
  • dateDate 對(duì)象、時(shí)間戳或日期字符串。
  • 函數(shù)返回一個(gè)新的 Date 對(duì)象,時(shí)間部分設(shè)置為結(jié)束時(shí)間。

判斷日期是否在范圍內(nèi)

判斷一個(gè)日期是否在指定的日期范圍內(nèi)。

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;
}
  • date 是待檢查的日期。
  • startDateendDate 是范圍的起始和結(jié)束日期。
  • 函數(shù)返回布爾值,表示日期是否在范圍內(nèi)。

獲取星期幾

獲取指定日期是星期幾,返回?cái)?shù)字或名稱。

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;
}
  • dateDate 對(duì)象、時(shí)間戳或日期字符串。
  • format 指定返回格式,'number' 返回 0-6(0 是周日),'name' 返回英文名稱。

獲取時(shí)間段的月份列表

獲取兩個(gè)日期之間的所有月份。

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;
}
  • startDateendDateDate 對(duì)象、時(shí)間戳或日期字符串。
  • 函數(shù)返回一個(gè)數(shù)組,包含該時(shí)間段內(nèi)的所有月份。

時(shí)區(qū)轉(zhuǎn)換

將日期從一個(gè)時(shí)區(qū)轉(zhuǎn)換到另一個(gè)時(shí)區(qū)。

function convertTimeZone(date, targetTimeZone) {
  const options = { timeZone: targetTimeZone };
  return new Date(date.toLocaleString('en-US', options));
}
  • dateDate 對(duì)象、時(shí)間戳或日期字符串。
  • targetTimeZone 是目標(biāo)時(shí)區(qū),如 'America/New_York'。
  • 函數(shù)返回轉(zhuǎn)換后的 Date 對(duì)象。

日期有效性檢查

檢查一個(gè)日期是否有效。

function isValidDate(date) {
  return date instanceof Date && !isNaN(date.getTime());
}
  • date 是待檢查的日期。
  • 函數(shù)返回布爾值,表示日期是否有效。

總結(jié)

以上封裝涵蓋了 JavaScript 日期時(shí)間處理的常見(jiàn)需求,包括格式化、解析、計(jì)算、比較和時(shí)區(qū)轉(zhuǎn)換等。通過(guò)合理封裝,可以減少重復(fù)代碼,提高開(kāi)發(fā)效率。實(shí)際使用時(shí),可以根據(jù)項(xiàng)目需求進(jìn)一步調(diào)整或擴(kuò)展這些函數(shù)。

相關(guān)文章

最新評(píng)論

广州市| 静海县| 长治县| 察雅县| 宣城市| 皋兰县| 兴安县| 安仁县| 钦州市| 句容市| 辉县市| 通州市| 平潭县| 东平县| 乾安县| 尚义县| 宜良县| 久治县| 望谟县| 德惠市| 兴仁县| 宁城县| 绵竹市| 朝阳区| 罗江县| 北川| 桐城市| 皋兰县| 满洲里市| 贵州省| 正宁县| 敦煌市| 湖口县| 威宁| 大同县| 横峰县| 施甸县| 彰化县| 阳西县| 防城港市| 岑巩县|