import { fillZero } from '@/utils/utils'
export const shortcuts = [['最近一周', 7],['最近一个月', 30],['最近三个月', 90],['最近半年', 180],['最近一年', 365]
]
export const dateParams = (value) => {const dateObj = value ? new Date(value) : new Date()const time = dateObj.getTime()const year = dateObj.getFullYear()const month = dateObj.getMonth()const date = dateObj.getDate()const day = dateObj.getDay()return {dateObj,year,month,date,day,time}
}
export const dateStartAndLast = (value) => {const startDate = value ? new Date(value) : new Date()startDate.setDate(1) const endDate = new Date(startDate)endDate.setMonth(startDate.getMonth() + 1)endDate.setDate(0) return {startDate: startDate.getDate(),startDay: startDate.getDay(),startMonth: startDate.getMonth(),startYear: startDate.getFullYear(),endDate: endDate.getDate(),endDay: endDate.getDay(),endMonth: endDate.getMonth(),endYear: endDate.getFullYear()}
}export const dateFormatter = (date) => {const dateObj = new Date(date)const year = `${dateObj.getFullYear()}`.padStart(4, '0')const month = `${dateObj.getMonth() + 1}`.padStart(2, '0')const day = `${dateObj.getDate()}`.padStart(2, '0')return `${year}-${month}-${day}`
}
export const dateRangeGen = (period, time) => {const end = time ? new Date(time) : new Date()const start = end - 3600 * 1000 * 24 * periodif (period === 1) {return [end, end].map(dateFormatter)}return [start, end].map(dateFormatter)
}
export const dateNaturalRangeGen = (period, time, isThan = false, timestamp = false) => {const { year, month, date, day } = dateParams()const end = time ? new Date(time) : new Date(year, month, isThan ? date : (date + (7 - day)))const days = isThan ? (day - 1) : (period - 1)const start = end - 3600 * 1000 * 24 * daysif (period === 1) {return [end, end].map(el => timestamp ? new Date(el).getTime() : dateFormatter(el))}return [start, end].map(el => timestamp ? new Date(el).getTime() : dateFormatter(el))
}export const pickerOptionGen = shortcuts => ({shortcuts: shortcuts.map(([text, period]) => ({text,onClick: picker => picker.$emit('pick', dateRangeGen(period))}))
})
export const millisecondFormatDate = (time, fmt = 'yyyy-MM-dd hh:mm:ss') => {const date = time ? new Date(time) : new Date()const o = {'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds(), 'q+': Math.floor((date.getMonth() + 3) / 3), 'S': date.getMilliseconds() }if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }for (const k in o) {if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }}return fmt
}export const getDateMapping = () => {const { year, month, date, day } = dateParams()const { endYear, endMonth, endDate } = dateStartAndLast(`${month ? year : year - 1}-${month || 12}-01`)const options = {1: { period: 7,time: 0},2: { period: day, time: new Date(year, month, date)},3: { period: 7,time: new Date(year, month, date - day)},4: { period: endDate,time: new Date(endYear, endMonth, endDate)},5: { period: dateStartAndLast(`${year}-${month + 1}-01`).endDate,time: (() => {const { endYear, endMonth, endDate } = dateStartAndLast(`${year}-${month + 1}-01`)return new Date(endYear, endMonth, endDate)})()},9: { period: 7,time: new Date(year, month, date)}}return {...options,'week': options[2],'cweek': options[1], 'pweek': options[3],'pmonth': options[4]}
}export const pickerGen = shortcuts => ({shortcuts: shortcuts.map(([text, period]) => {const dateOptions = getDateMapping()const result = {'week': 'cweek' }[period] || periodreturn {text,onClick: picker => picker.$emit('pick', dateNaturalRangeGen(dateOptions[result].period, dateOptions[result].time))}})
})const dateShortcuts = [['本周', 'week'],['上周', 'pweek'],['上月', 'pmonth']
]export const pickerOption = pickerGen(dateShortcuts)
export const getPreviousDay = (date = new Date()) => {const resetDate = new Date(date)const previous = new Date(resetDate.getTime())previous.setDate(resetDate.getDate() - 1)return dateFormatter(previous)
}
export function diffTimeDay(startTime, endTime) {const diffTime = endTime - startTimeconst daySecond = 24 * 3600 * 1000const day = Math.floor(diffTime / daySecond)const hourSecond = 3600 * 1000var dayRemainder = diffTime % daySecond var hour = Math.floor(dayRemainder / hourSecond)var hourRemainder = dayRemainder % hourSecond var minute = Math.floor(hourRemainder / (60 * 1000))var minuteRemainder = hourRemainder % (60 * 1000) var second = Math.round(minuteRemainder / 1000)return {day,hour,minute,second}
}
export function dateFilter(dateString) {const noTime = ['0000-00-00 0:0:0', '0000-00-00 00:00:00', '0001-1-1 0:0:0', '0001-1-1 00:00:00', '0001-01-01 0:0:0', '0001-01-01 00:00:00', '0000-00-00', '0001-01-01'].includes(dateString)if (noTime || !dateString && dateString !== 0) {return '-'}return dateString
}export function parseTime(time, cFormat) {if (arguments.length === 0) {return null}const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'let dateif (typeof time === 'object') {date = time} else {if (('' + time).length === 10) time = parseInt(time) * 1000date = new Date(time)}const formatObj = {y: date.getFullYear(),m: date.getMonth() + 1,d: date.getDate(),h: date.getHours(),i: date.getMinutes(),s: date.getSeconds(),a: date.getDay()}const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {let value = formatObj[key]if (key === 'a') {return ['日', '一', '二', '三', '四', '五', '六'][value]}if (result.length > 0 && value < 10) {value = '0' + value}return value || 0})return time_str
}export const hasDateBeenFormatted = (format = 'yy-mm-dd hh:mm:ss') => {const result = format.toLocaleLowerCase()return {hasYear: result.includes('yy'),hasMonth: result.includes('-mm'),hasDay: result.includes('-dd'),hasHour: result.includes('hh'),hasMinute: result.includes(':mm'),hasSecond: result.includes(':ss')}
}
export const formatDate = (time, format = 'YY-MM-DD') => {if (time < 0 || !time) {return []}const data = new Date(time)const year = data.getFullYear()const month = data.getMonth() + 1const day = data.getDate()const hour = data.getHours()const minute = data.getMinutes()const second = data.getSeconds()const { hasYear, hasMonth, hasDay, hasHour, hasMinute, hasSecond } = hasDateBeenFormatted(format)return {...hasYear && year ? { year } : {},...hasMonth && month ? { month: fillZero(month) } : {},...hasDay && day ? { day: fillZero(day) } : {},...hasHour && hour ? { hour: fillZero(hour) } : {},...hasMinute && minute ? { minute: fillZero(minute) } : {},...hasSecond && second ? { second: fillZero(second) } : {}}
}export const converTimeObjectToString = (time, format = 'YY-MM-DD') => {const data = formatDate(time, format)const arrData = Object.keys(data)const dataLen = arrData.length - 1return arrData.reduce((acc, cur, index) => {const symbol = index < 2 ? '-' : index === 2 || index === dataLen ? ' ' : ':'return (acc += `${data[cur]}${symbol}`)}, '')
}
export const converTimeStringToWeekArray = time => {const data = new Date(time)const timesStamp = data.getTime()const currentDay = data.getDay()return Array.from(new Array(7), (value, index) => index).reduce((acc, cur) => [...acc,...[new Date(timesStamp + 24 * 60 * 60 * 1000 * (cur - (currentDay + 7) % 7)).toLocaleDateString().replace(/\//g, '-').replace(/(\d+)/g, $1 => fillZero($1))]], [])
}