1.格式化时间
/**
* 格式化日期
* @param date
* @param format
* @return {string}
*/
export function useFormatTime (date, fmt = 'YYYY-MM-DD') {
if (!date) {
return
}
if (typeof date === 'string') {
const time = Number(date)
if (isNaN(time)) date = new Date(date)
else {
date = new Date(Number(date))
}
}
if (typeof date === 'number') {
date = new Date(date)
}
let ret
const opt = {
'Y+': date.getFullYear().toString(), // 年
'M+': (date.getMonth() + 1).toString(), // 月
'D+': date.getDate().toString(), // 日
'H+': date.getHours().toString(), // 时
'm+': date.getMinutes().toString(), // 分
's+': date.getSeconds().toString() // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
}
for (const k in opt) {
ret = new RegExp('(' + k + ')').exec(fmt)
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
)
}
}
return fmt
}
2.判断当前是该年的第几周
/**
* 判断当前是该年的第几周
* @param {*} date
* @returns
*/
export function useWeekOnYears (date) {
const year = date.getFullYear() // 获取年
const month = date.getMonth() + 1 // 获取月
const day = date.getDate() // 获取天
const isLeapYear = (year % *** === 0) || (year % 4 === 0 && year % 100 !== 0) // 判断是否为闰年
const second = isLeapYear ? 29 : 28
const monthList = [31, second, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].splice(0, month - 1) // 获取月份数组
let currentDays = '' // 当前日期天数
let currentWeek = '' // 当前周数
// 计算天数
currentDays = month === 1 ? day : (monthList.reduce((t, v) => {
return t + v
}, 0)) + day
// 计算是第几周
currentWeek = currentDays % 7 === 0 ? currentDays / 7 : Math.ceil(currentDays / 7)
return {
year,
currentWeek
}
}
65 天前