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

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

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

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

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

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

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

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

格式化日期

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

解析日期字符串

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

計算日期差

計算兩個日期之間的差值,返回天、小時、分鐘或秒。

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 對象或時間戳。
  • unit 參數(shù)指定返回的單位,支持 dayhour、minutesecond。
  • 函數(shù)返回兩個日期之間的整數(shù)差值。

日期加減

對日期進行加減操作,支持年、月、日等單位。

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

獲取月份的天數(shù)

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

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

判斷是否為閏年

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

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 開始。
  • 函數(shù)返回 1 到 4 之間的整數(shù),表示季度。

時間戳轉(zhuǎn)日期

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

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

日期轉(zhuǎn)時間戳

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

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 對象、時間戳或日期字符串。
  • unit 指定返回的時間戳單位,默認(rèn)為毫秒('ms'),傳入 's' 則返回秒級。

判斷日期是否相等

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

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

獲取當(dāng)前時間的零點

獲取當(dāng)前日期的零點時間(00:00:00)。

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

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

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

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

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

判斷一個日期是否在指定的日期范圍內(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)。

獲取星期幾

獲取指定日期是星期幾,返回數(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 對象、時間戳或日期字符串。
  • format 指定返回格式,'number' 返回 0-6(0 是周日),'name' 返回英文名稱。

獲取時間段的月份列表

獲取兩個日期之間的所有月份。

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

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

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

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

日期有效性檢查

檢查一個日期是否有效。

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

總結(jié)

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

相關(guān)文章

最新評論

沧源| 永清县| 临朐县| 交城县| 武功县| 岚皋县| 雅江县| 汪清县| 织金县| 彭泽县| 英超| 郯城县| 高碑店市| 株洲市| 常熟市| 双辽市| 彭山县| 湟中县| 腾冲县| 灵川县| 江陵县| 成安县| 满洲里市| 克什克腾旗| 乌苏市| 涞源县| 民丰县| 得荣县| 屏山县| 高阳县| 郓城县| 沛县| 江津市| 响水县| 诸暨市| 安仁县| 钟祥市| 安化县| 白银市| 武鸣县| 滕州市|