import dayjs from 'dayjs' import 'dayjs/locale/zh-cn' import weekday from 'dayjs/plugin/weekday' // 配置 dayjs dayjs.locale('zh-cn') dayjs.extend(weekday) export const calcDate = (date1, date2) => { let date3 = date2 - date1 let days = Math.floor(date3 / (24 * 3600 * 1000)) let leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数 let hours = Math.floor(leave1 / (3600 * 1000)) let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数 let minutes = Math.floor(leave2 / (60 * 1000)) let leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数 let seconds = Math.round(date3 / 1000) return { leave1, leave2, leave3, days: days, hours: hours, minutes: minutes, seconds: seconds, } } /** * 日期格式化 */ export function dateFormat(date, format) { format = format || 'yyyy-MM-dd hh:mm:ss' if (date !== 'Invalid Date') { let o = { 'M+': date.getMonth() + 1, //month 'd+': date.getDate(), //day 'h+': date.getHours(), //hour 'm+': date.getMinutes(), //minute 's+': date.getSeconds(), //second 'q+': Math.floor((date.getMonth() + 3) / 3), //quarter S: date.getMilliseconds(), //millisecond } if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) for (let k in o) if (new RegExp('(' + k + ')').test(format)) format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)) return format } return '' } /** * 当前时间戳 */ export function dateNow() { return dateFormat(new Date(), 'yyyyMMddhhmmss') } // 获取时间戳对应的日期 export const getDateFromTimestamp = timestamp => { const date = new Date(timestamp) const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hours = date.getHours() const minutes = date.getMinutes() const seconds = date.getSeconds() return { year, month, day, hours, minutes, seconds } } /** * 根据给定的时间单位,返回对应的时间范围。 * * @param {string} unit - 时间单位,可选值为 'today'、'week'、'month'、'year'。 * @param formatStr -- 格式类型 * @returns {Array} 返回一个包含两个元素的数组,第一个元素是时间范围的开始时间,第二个元素是当前时间。 * 时间格式为 'YYYY-MM-DD HH:mm:ss'。 */ export const getDateRange = (unit, formatStr = 'YYYY-MM-DD HH:mm:ss') => { const todayDate = dayjs() let returnArr = [dayjs(), todayDate] if (unit === 'today') { returnArr = [dayjs(), todayDate] } if (unit === 'week') { returnArr = [dayjs().weekday(0), todayDate] } if (unit === 'month') { returnArr = [dayjs().startOf('month'), todayDate] } if (unit === 'year') { returnArr = [dayjs().startOf('year'), todayDate] } returnArr = [returnArr[0].startOf('day').format(formatStr), returnArr[1].endOf('day').format(formatStr)] return returnArr }