JS 对时间日期的转换与操作
JS 时间格式转换this.timeFormatConvert(new Date()) // 2022-11-26 21:37:29/** 时间格式转换 * param e 要转换的日期(如Sat Nov 26 2022 21:37:29 GMT0800 (中国标准时间)) * returns {string} 转换结果(如2022-11-26 21:37:29) */ timeFormatConvert(e) { const Y e.getFullYear(); // 年 const M this.prefixZero(e.getMonth() 1); // 月 const D this.prefixZero(e.getDate()); // 日 const H this.prefixZero(e.getHours()); // 时 const Mi this.prefixZero(e.getMinutes()); // 分 const S this.prefixZero(e.getSeconds()); // 秒 return Y - M - D H : Mi : S; }, prefixZero(num 0, n 2) { // 数字位数不够数字前面补零 return (Array(n).join(0) num).slice(-n); },JS 获取当前年月日时分秒this.getCurrTime(noGap) // 20221129154229this.getCurrTime() // 2022-11-29 15:44:20/** 获取当前年月日时分秒 * param e 默认.年月日时分秒 date.年月日 dateTime.年月日时分 noGap.无分隔符的年月日时分秒 * returns {string} */ getCurrTime(e ) { const curDate new Date(), T { Y: curDate.getFullYear().toString(), // 年 M: this.prefixZero(curDate.getMonth() 1), // 月 D: this.prefixZero(curDate.getDate()), // 日 H: this.prefixZero(curDate.getHours()), // 时 Mi: this.prefixZero(curDate.getMinutes()), // 分 S: this.prefixZero(curDate.getSeconds()), // 秒 }, tDate T.Y - T.M - T.D; // 年月日 let result tDate T.H : T.Mi : T.S; // 年月日时分秒 if (e date) result tDate; // 年月日 if (e dateTime) result tDate T.H : T.Mi; // 年月日时分 if (e noGap) result T.Y T.M T.D T.H T.Mi T.S; // 无分隔符 return result; }, prefixZero(num 0, n 2) { // 数字位数不够数字前面补零 return (Array(n).join(0) num).slice(-n); },JS 获取n天前或n天后的日期当前日期2022-11-277天后的日期this.getAgoLaterDate(7) // 2022-12-047天前的日期this.getAgoLaterDate(-7) // 2022-11-20/** 获取n天前或n天后的日期(默认当天) * param n 需要的天数(n之后的日期-n之前的日期) * returns {string} 默认返回当前日期 */ getAgoLaterDate(n 0) { const curTime new Date(), D1 curTime.getDate(), date new Date(curTime); date.setDate(D1 n); const Y2 date.getFullYear(), M2 this.prefixZero(date.getMonth() 1), D2 this.prefixZero(date.getDate()); return Y2 - M2 - D2; }, prefixZero(num 0, n 2) { // 数字位数不够数字前面补零 return (Array(n).join(0) num).slice(-n); },JS 获取指定日期的周一和周日this.getSpecifyMonSun() // {mon: 2022-11-21, sun: 2022-11-27}this.getSpecifyMonSun(2022/11/17) // {mon: 2022-11-14, sun: 2022-11-20}/** 获取指定日期的周一和周日(默认当前日期) * param e 需要指定的日期(格式yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd) * returns {{mon: string, sun: string}} 默认返回当前日期的周一和周末日期 */ getSpecifyMonSun(e new Date()) { const that this, now new Date(e), nowTime now.getTime(), day now.getDay() || 7, // 周日时day修改为7否则获取的是下周一到周日的日期 oneDayTime 24 * 60 * 60 * 1000, // 一天的毫秒(ms)数 mondayTime new Date(nowTime - (day - 1) * oneDayTime), //周一的日期 sundayTime new Date(nowTime (7 - day) * oneDayTime); //周日的日期 function dataFormat(d) { const Y d.getFullYear(), // 年 M that.prefixZero(d.getMonth() 1), // 月 D that.prefixZero(d.getDate()); // 日 return Y - M - D; } return { mon: dataFormat(mondayTime), sun: dataFormat(sundayTime) }; }, prefixZero(num 0, n 2) { // 数字位数不够数字前面补零 return (Array(n).join(0) num).slice(-n); },JS 获取指定日期的周一至周日的所有日期this.getSpecifyWeekAllTime() // [2023-01-30, 2023-01-31, 2023-02-01, 2023-02-02, 2023-02-03, 2023-02-04, 2023-02-05]this.getSpecifyWeekAllTime(2023-01-19) // [2023-01-16, 2023-01-17, 2023-01-18, 2023-01-19, 2023-01-20, 2023-01-21, 2023-01-22]/** 获取指定日期的周一至周日的所有日期 * param e 需要指定的日期(格式yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd) * param t date.只返回月与日(默认返回年月日) * returns {*[]} 默认返回当前日期的周一至周日的所有日期 */ getSpecifyWeekAllTime(e new Date(), t ) { const timeStamp new Date(e).getTime(), curDay new Date(e).getDay(), dateList []; for (let i 0; i 7; i) { const das new Date(timeStamp 24 * 60 * 60 * 1000 * (i - ((curDay 6) % 7))); const Y das.getFullYear(), // 年 M this.prefixZero(das.getMonth() 1), // 月 D this.prefixZero(das.getDate()); // 日 let val Y - M - D; if (t date) val M - D; dateList.push(val); } return dateList; }, prefixZero(num 0, n 2) { // 数字位数不够数字前面补零 return (Array(n).join(0) num).slice(-n); },JS 获取指定日期的月初和月末this.getSpecifyEarlyEndMonth() // {first: 2022-11-01, end: 2022-11-30}this.getSpecifyEarlyEndMonth(2022/09) // {first: 2022-09-01, end: 2022-09-30}/** 获取指定日期的月初和月末(默认当前月) * param e 需要指定的日期(格式yyyy-MM 或 yyyy/MM 或 yyyy.MM) * returns {{end: string, first: string}} 默认返回当前月的月初和月末日期 */ getSpecifyEarlyEndMonth(e new Date()) { const that this, nowDate new Date(e), // 当前日期 year nowDate.getFullYear(), // 指定年 month nowDate.getMonth() 1, // 指定月 oneDayTime 24 * 60 * 60 * 1000, // 一天的毫秒(ms)数 firstDay new Date(year, month - 1), // 当月第一天的日期 lastDay new Date(new Date(year, month).valueOf() - oneDayTime); // 当月最后一天的日期 function dataFormat(d) { const Y d.getFullYear(), // 年 M that.prefixZero(d.getMonth() 1), // 月 D that.prefixZero(d.getDate()); // 日 return Y - M - D; } return { first: dataFormat(firstDay), end: dataFormat(lastDay) }; }, prefixZero(num 0, n 2) { // 数字位数不够数字前面补零 return (Array(n).join(0) num).slice(-n); },JS 获取指定年份季度的开始和结束日期this.getSpecifyQuarter(); // { first: 2023-01-01, end: 2023-03-31 }/** 获取指定年份季度的开始和结束日期(默认今年的第一季度) * param year 指定的年份 * param qtr 指定的季度 * returns {{end: string, first: string}} 默认返回今年第一季度的日期 */ getSpecifyQuarter(year new Date().getFullYear(), qtr 1) { let val 0; // 第一季度 if (qtr 2) { val 3; // 第二季度 } else if (qtr 3) { val 6; // 第三季度 } else if (qtr 4) { val 9; // 第四季度 } const startDate new Date(year, val, 1); const endDate new Date(year, val 2, getMonthDays(year, val 2)); // 日期格式化 function dataFormat(d) { const Y d.getFullYear(), // 年 M prefixZero(d.getMonth() 1), // 月 D prefixZero(d.getDate()); // 日 return Y - M - D; } // 数字位数不够数字前面补零 function prefixZero(num 0, n 2) { return (Array(n).join(0) num).slice(-n); } // 获得指定月份的天数 function getMonthDays(y, m) { const monthStart new Date(y, m, 1); const monthEnd new Date(y, m 1, 1); return (monthEnd - monthStart) / (1000 * 60 * 60 * 24); } return { first: dataFormat(startDate), end: dataFormat(endDate) }; },JS 根据当前时间判断是早上、中午、下午this.getCurTimeState() // 晚上好/** 根据当前时间判断是早上、中午、下午 * returns {string} 返回当前时间段对应的状态 */ getCurTimeState() { const nowTime new Date(), // 获取当前时间 hour nowTime.getHours(); // 获取当前小时 let result ; // 设置默认文字 // 判断当前时间段 if (hour 0 hour 10) { result 早上好; } else if (hour 10 hour 14) { result 中午好; } else if (hour 14 hour 18) { result 下午好; } else if (hour 18 hour 24) { result 晚上好; } return result; // 返回当前时间段对应的状态 },JS 将年月日时分秒转化为刚刚几分钟前几小时前几天前等this.timeConvertReveal(2020-11-27 14:38:16) // 2年前this.timeConvertReveal() // 刚刚/** 将年月日时分秒转化为刚刚几分钟前几小时前几天前等(默认刚刚) * param e 需要转换的时间(格式yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss) * returns {string} 默认返回刚刚 */ timeConvertReveal(e new Date()) { const minute 1000 * 60, // 分钟 hour minute * 60, // 小时 day hour * 24, // 天 week day * 7, // 周 month day * 30, // 月 year month * 12, // 年 curTime new Date().getTime(), // 当前时间的时间戳 specifyTime new Date(e), // 指定时间的时间戳 mistiming curTime - specifyTime, // 时间差 yearDiffer mistiming / year, // 年差 monthDiffer mistiming / month, // 月差 weekDiffer mistiming / week, // 周差 dayDiffer mistiming / day, // 天差 hourDiffer mistiming / hour, // 时差 minuteDiffer mistiming / minute; // 分钟差 let result -; if (yearDiffer 1) result toInt(yearDiffer) 年前; else if (monthDiffer 1) result toInt(monthDiffer) 月前; else if (weekDiffer 1) result toInt(weekDiffer) 周前; else if (dayDiffer 1) result toInt(dayDiffer) 天前; else if (hourDiffer 1) result toInt(hourDiffer) 小时前; else if (minuteDiffer 1) result toInt(minuteDiffer) 分钟前; else result 刚刚; function toInt(num) { return parseInt(num.toString()); } return result; },JS 获得指定月份的天数this.getMonthDays(2022-10) // 31/** 获得指定月份的天数(默认当前月) * param e 需要指定的日期(格式yyyy-MM 或 yyyy/MM 或 yyyy.MM) * returns {number} 默认返回当前月的天数 */ getMonthDays(e new Date()) { const now new Date(e), // 指定日期 nowYear now.getYear(), // 指定年份 nowMonth now.getMonth(), // 指定月份 startDate new Date(nowYear, nowMonth, 1), // 开始日期 endDate new Date(nowYear, nowMonth 1, 1); // 结束日期 return (endDate - startDate) / (1000 * 60 * 60 * 24); },JS 获取指定日期是周几this.getCurrWeek(2022-11-24) // 周四this.getCurrWeek() // 周二/** 获取指定日期是周几 * param e 需要指定的日期(格式yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd) * returns {string} 默认返回当前日期是周几 */ getCurrWeek(e new Date()) { const day new Date(e).getDay(), weeks [周日, 周一, 周二, 周三, 周四, 周五, 周六]; return weeks[day]; },JS 计算两个时间的时间差this.getTimeDiff(2022-11-28 19:30:24) // {text: 时间已超过30分钟, timeDiff: 0天21时28分40秒40毫秒, dateObj: {day: 0, hour: 21, min: 28, sec: 40, ms: 40}}/** 计算两个时间的时间差(timeDiff返回格式为xx天xx时xx分xx秒xx毫秒) * param startTime 开始时间(格式yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [需小于结束时间]) * param endTime 结束时间(格式yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [默认当前时间]) * returns {string|{timeDiff: string, text: string, dateObj: {sec: number, min: number, hour: number, ms: number, day: number}}} */ getTimeDiff(startTime, endTime new Date()) { if (!startTime) return 错误开始时间为必填; const diffVal new Date(endTime) - new Date(startTime); // 两个时间戳相差的毫秒数 if (diffVal 0) return 错误开始时间大于结束时间; const day Math.floor(diffVal / (24 * 3600 * 1000)), // 计算相差的天数 remainDay diffVal % (24 * 3600 * 1000), // 计算天数后剩余的毫秒数 hour Math.floor(remainDay / (3600 * 1000)), // 计算相差的小时数 remainHour remainDay % (3600 * 1000), // 计算小时数后剩余的毫秒数 min Math.floor(remainHour / (60 * 1000)), // 计算相差的分钟数 remainMinute remainHour % (60 * 1000), // 计算分钟数后剩余的毫秒数 sec Math.round(remainMinute / 1000), // 计算相差的秒数 remainSeconds remainMinute % (60 * 1000), // 计算秒数后剩余的毫秒数 ms Math.round(remainSeconds / 1000), // 计算相差的毫秒数 time day 天 hour 时 min 分 sec 秒 ms 毫秒, obj { day: day, hour: hour, min: min, sec: sec, ms: ms }; let val 时间未超过30分钟; if (min 30 || hour 1) val 时间已超过30分钟; return { text: val, timeDiff: time, dateObj: obj }; },JS 从日期字符串中截取出年、月、日、时、分、秒this.captureTime() // {day: 29, hour: 17, minute: 40, month: 11, second: 06, year: 2022}this.captureTime(2020-12-11 14:54:48) // {day: 11, hour: 14, minute: 54, month: 12, second: 48, year: 2020}/** 从日期字符串中截取出年、月、日、时、分、秒 * param e 需要截取的日期(格式yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [默认当前日期]) * returns {{month: *, hour: *, year: *, day: *, minute: *, second: *}} 默认返回当前日期 */ captureTime(e null) { let time e; if (!e) { const curDate new Date(), T { Y: curDate.getFullYear().toString(), // 年 M: this.prefixZero(curDate.getMonth() 1), // 月 D: this.prefixZero(curDate.getDate()), // 日 H: this.prefixZero(curDate.getHours()), // 时 Mi: this.prefixZero(curDate.getMinutes()), // 分 S: this.prefixZero(curDate.getSeconds()), // 秒 }; time T.Y - T.M - T.D T.H : T.Mi : T.S; } const timeArr time.replace(/[:. /]/g, -).split(-); // 将:. /换为-再根据-分组 return { year: timeArr[0], // 年 month: timeArr[1], // 月 day: timeArr[2], // 日 hour: timeArr[3], // 时 minute: timeArr[4], // 分 second: timeArr[5], // 秒 }; }, prefixZero(num 0, n 2) { // 数字位数不够数字前面补零 return (Array(n).join(0) num).slice(-n); },JS 判断指定日期是否在指定区间内this.isDateBetween(2023.9.27 10:30:00, 2023.9.20 10:30:00, 2023.9.30 10:30:00) // truethis.isDateBetween(2023.9.17 10:30:00, 2023.9.20 10:30:00, 2023.9.30 10:30:00) // false/** 判断指定日期是否在指定区间内 * param dateStr 指定日期 * param startDateStr 区间开始日期 * param endDateStr 区间结束日期 * returns {Boolean} true.在区间内 false.不在区间内 */ isDateBetween(dateStr, startDateStr, endDateStr) { if (!dateStr || !startDateStr || !endDateStr) return; let flag false; const startFlag dateCompare(dateStr, startDateStr) 1; const endFlag dateCompare(dateStr, endDateStr) -1; if (startFlag endFlag) flag true; return flag; }, /** 日期大小的比较 * param dateStr 日期 * param compareDateStr 比较的日期 * returns {Number} 1.未开始 0.进行中 -1.已结束 */ dateCompare(dateStr, compareDateStr) { if (!dateStr || !compareDateStr) return; const dateTime new Date(dateStr).getTime(); const compareDateTime new Date(compareDateStr).getTime(); if (compareDateTime dateTime) { return 1; } else if (compareDateTime dateTime) { return 0; } else { return -1; } },JS 获取指定月份的所有日期(包括起止两端)/** * 获取指定月份的所有日期包括起止两端 * param {Object} [options] 可选配置对象 * param {Date|string|number} [options.referenceDate] 用来确定“哪一个月”。如果省略则使用当前时间。 * param {boolean} [options.onlyToTodayfalse] 为 true 时只返回 1 号到今天仅当查询月份为当前月份时生效。 * param {date|string} [options.formatdate] 返回值的类型date 返回 Date 对象string 返回 YYYY-MM-DD 格式的字符串。 * returns {ArrayDate|string} 指定月份的所有日期 * * example * getMonthDays(); // → [Date(2024‑07‑01), Date(2024‑07‑02), …] // 当前月的所有日期默认 * getMonthDays({ referenceDate: 2023-02-15 }); // 指定日期2023‑02‑15所在月份的所有日期 * getMonthDays({ onlyToToday: true, format: string }); // 只取当前月份 1 号到今天假设今天是 2024‑07‑13 * getMonthDays({ referenceDate: 2022-11-20, onlyToToday: true }); // 指定月份只取 1 号到今天月份不是当前月份时仍返回整月 */ getMonthDays({ referenceDate new Date(), onlyToToday false, format string } {}) { // ---------- 参数准备 ---------- const ref new Date(referenceDate); if (Number.isNaN(ref.getTime())) throw new Error(Invalid referenceDate supplied.); // 当月的第一天本地时间0点 const start new Date(ref.getFullYear(), ref.getMonth(), 1); // 当月的最后一天 let end new Date(ref.getFullYear(), ref.getMonth() 1, 0); // 第0天 前月最后一天 // 是否只取到今天仅当查询的月份是当前月份时才限制 if (onlyToToday) { const today new Date(); // 当前时间 const todayMidnight new Date(today.getFullYear(), today.getMonth(), today.getDate()); // 如果查询的月份正好是「本月」则把结束日期限制为「今天」 if (todayMidnight.getFullYear() ref.getFullYear() todayMidnight.getMonth() ref.getMonth()) { end todayMidnight; } // 否则仍返回整月因为「今天」不在该月份内部 } // ---------- 生成结果 ---------- const result []; const cur new Date(start); // copy while (cur end) { if (format string) { const y cur.getFullYear(); const m String(cur.getMonth() 1).padStart(2, 0); const d String(cur.getDate()).padStart(2, 0); result.push(${y}-${m}-${d}); } else { // 返回 Date 实例的拷贝防止外部误改 result.push(new Date(cur)); } // 日期向后推一天 cur.setDate(cur.getDate() 1); } return result; }