加载中...
日期方法⏰
第1节:AI工具推荐
第2节:日期方法⏰
第3节:js浮点数计算
课文封面

如何用 JavaScript 实现日期格式化?
如何用 JavaScript 计算两个日期之间的差值?
如何用 JavaScript 比较两个日期的大小?
如何用 JavaScript 实现日期的加减操作?

js日期格式化

formatDate 是一个用于将日期对象格式化为指定字符串格式的实用函数。它支持传入 Date 对象或日期字符串作为参数,并允许自定义输出格式(如 YYYY-MM-DD, MM/DD/YYYY, HH:mm:ss 等)。通过简单的配置,可以轻松完成各种日期格式化需求。

/** * 日期格式化 * @param {string|Date|number} date - 日期,可以是字符串(如 'YYYY-MM-DD'),时间戳或 Date 对象 * @param {string} format - 格式字符串,例如 'YYYY-MM-DD HH:mm:ss' * @returns {string} 格式化后的日期字符串 */ function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') { // 将输入统一转换为 Date 对象 const curDate = new Date(date); if (isNaN(curDate.getTime())) { throw new Error('Invalid date. Please provide a valid Date object or date string.'); } const year = curDate.getFullYear(); const month = addLeadingZero(curDate.getMonth() + 1); // 月份从0开始,需要+1 const day = addLeadingZero(curDate.getDate()); const hours = addLeadingZero(curDate.getHours()); const minutes = addLeadingZero(curDate.getMinutes()); const seconds = addLeadingZero(curDate.getSeconds()); return format .replace('YYYY', year) .replace('MM', month) .replace('DD', day) .replace('HH', hours) .replace('mm', minutes) .replace('ss', seconds); } function addLeadingZero(num) { return ('0' + num).slice(-2); // 在数字前加 '0',然后取最后两位 } // 示例 const now = new Date(); console.log(formatDate(now, 'YYYY-MM-DD')); // 输出:2025-02-11 console.log(formatDate(now, 'YYYY/MM/DD HH:mm:ss')); // 输出:2025-02-11 12:30:45 console.log(formatDate('2025-12-31', 'YYYY年MM月DD日')); // 输出:2025年12月31日

js日期加减

adjustDate 是一个用于实现日期加减操作的实用函数。它支持传入 Date 对象或日期字符串作为参数,并允许指定加减的时间单位(如年、月、天、小时、分钟、秒)。通过简单的配置,可以轻松完成各种日期加减需求。

/** * 日期加减 * @param {string|Date|number} date - 日期,可以是字符串(如 'YYYY-MM-DD'),时间戳或 Date 对象 * @param {number} value - 加减的值 * @param {string} unit - 单位,支持 'year', 'month', 'day', 'hour', 'minute', 'second' * @returns {Date} 加减后的日期对象 */ function adjustDate(date, value, unit = 'day') { // 将输入统一转换为 Date 对象 const result = new Date(date); if (isNaN(result.getTime())) { throw new Error('Invalid date. Please provide a valid Date object or date string.'); } // 校验 unit 参数 const validUnits = ['year', 'month', 'day', 'hour', 'minute', 'second']; if (!validUnits.includes(unit)) { throw new Error(`Invalid unit: ${unit}`); } // 执行日期加减操作 switch (unit) { case 'year': result.setFullYear(result.getFullYear() + value); break; case 'month': result.setMonth(result.getMonth() + value); break; case 'day': result.setDate(result.getDate() + value); break; case 'hour': result.setHours(result.getHours() + value); break; case 'minute': result.setMinutes(result.getMinutes() + value); break; case 'second': result.setSeconds(result.getSeconds() + value); break; default: throw new Error('Invalid unit'); } return result; } const now = new Date(); console.log(adjustDate(now, 1, 'year')); // 当前日期加一年 console.log(adjustDate(now, -7, 'day')); // 当前日期减七天 console.log(adjustDate(now, 30, 'minute')); // 当前日期加三十分钟

js日期大小比较

compareDate 是一个用于比较两个日期大小的实用函数。它支持传入 Date 对象或日期字符串作为参数,并返回比较结果:-1(第一个日期小于第二个日期)、0(两个日期相等)或 1(第一个日期大于第二个日期)。

/** * 比较两个日期(支持字符串或日期对象) * @param {string|Date} date1 - 第一个日期,可以是字符串或 Date 对象 * @param {string|Date} date2 - 第二个日期,可以是字符串或 Date 对象 * @returns {number} 返回 -1(date1 < date2)、0(date1 == date2)、1(date1 > date2) */ function compareDate(date1, date2) { // 辅助函数:将输入转换为有效的 Date 对象 function toDate(input) { const result = new Date(input); if (isNaN(result.getTime())) { throw new Error(`Invalid date: ${input}`); } return result; } // 将参数转换为 Date 对象 const d1 = toDate(date1); const d2 = toDate(date2); // 比较时间戳 const time1 = d1.getTime(); const time2 = d2.getTime(); if (time1 < time2) return -1; if (time1 > time2) return 1; return 0; } // 使用 Date 对象 const dateA = new Date('2025-01-01'); const dateB = new Date('2025-01-15'); console.log(compareDate(dateA, dateB)); // 输出 -1 // 使用日期字符串 console.log(compareDate('2025-01-15', '2025-01-01')); // 输出 1 console.log(compareDate('2025-01-01', '2025-01-01')); // 输出 0

js计算日期差

dateDiff 是一个用于计算两个日期之间差值的实用函数。它支持多种时间单位(如天、小时、分钟、秒),并可以灵活处理 Date 对象或日期字符串作为输入参数。
返回结果为整数,并采用向下取整的方式(可通过修改 Math.floor() 调整取整逻辑)。

/** * 计算日期差 * @param {string|Date} date1 - 第一个日期,可以是字符串或 Date 对象 * @param {string|Date} date2 - 第二个日期,可以是字符串或 Date 对象 * @param {string} unit - 单位,支持 'day', 'hour', 'minute', 'second' * @returns {number} 日期差值 */ function dateDiff(date1, date2, unit = 'day') { // 辅助函数:将输入转换为有效的 Date 对象 function toDate(input) { const result = new Date(input); if (isNaN(result.getTime())) { throw new Error(`Invalid date: ${input}`); } return result; } // 将参数转换为 Date 对象 const d1 = toDate(date1); const d2 = toDate(date2); // 计算时间差(毫秒) const diff = d2.getTime() - d1.getTime(); // 根据单位计算差值 switch (unit) { case 'day': return Math.floor(diff / (1000 * 60 * 60 * 24)); case 'hour': return Math.floor(diff / (1000 * 60 * 60)); case 'minute': return Math.floor(diff / (1000 * 60)); case 'second': return Math.floor(diff / 1000); default: throw new Error('Invalid unit'); } } // 使用 Date 对象 const dateA = new Date('2025-01-01'); const dateB = new Date('2025-01-15'); console.log(dateDiff(dateA, dateB, 'day')); // 输出 14 // 使用日期字符串 console.log(dateDiff('2025-01-01', '2025-01-02', 'hour')); // 输出 24 console.log(dateDiff('2025-01-01T00:00:00', '2025-01-01T01:30:00', 'minute')); // 输出 90