You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

103 lines
2.9 KiB

export function getWeek(time : Date) {
let week = time.getDay() // 当前周几
// week = (week - 1) < 0 ? 0 : (week - 1)
if(week == 0) week = 7 // 0 表示周日
return week
}
export function getCurrentMonth(time : Date) : number {
let month = time.getMonth() + 1
return month
}
export function getLastMonth(curDate : Date) {
let lastDate = new Date()
lastDate.setMonth(curDate.getMonth() - 1)
return lastDate
}
export function getLastMonthDay(curDate : Date, offset : number) {
let lastDate = new Date(curDate.getTime())
lastDate.setHours(-24 * offset);
return lastDate
}
export function getNextMonthDay(curDate : Date, offset : number) {
let lastDate = new Date(curDate.getTime())
lastDate.setHours(24 * offset);
return lastDate
}
export function format(time : Date) {
return `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}`
}
export function formatFull(time : Date) {
const year = (time.getFullYear()) + ""
const month = (time.getMonth() + 1) + ""
const date = (time.getDate()) + ""
const hour = (time.getHours()) + ""
const minute = (time.getMinutes()) + ""
const second = (time.getSeconds()) + ""
return `${year}-${month.padStart(2, '0')}-${date.padStart(2, '0')} ${hour.padStart(2, '0')}:${minute.padStart(2, '0')}:${second.padStart(2, '0')}`
}
// 获取当前月份应该有多少天
export function getCurMonthDayNum(time : Date) : number {
let day = 31;
let month = time.getMonth() + 1
let year = time.getFullYear()
if ([1, 3, 5, 7, 8, 10, 12].indexOf(month) != -1) {
day = 31;
} else if ([4, 6, 9, 11].indexOf(month) != -1) {
day = 30;
} else if (year % 4 == 0) {
day = 29
} else {
day = 28
}
return day
}
export function generateDate<T = Date>(_nowDate : Date | string | number, format : (date : Date) => T = (v : Date) => (v as T)) {
if (typeof _nowDate === "string" || typeof _nowDate === "number") {
_nowDate = new Date(_nowDate as string)
}
const allDate : T[] = []
let firstDate = new Date(_nowDate.getTime())
firstDate.setDate(1)
const firstWeek = getWeek(firstDate)
console.log(firstDate.getTime());
for (var i = 1; i < firstWeek; i++) {
const date = getLastMonthDay(firstDate, i)
allDate.unshift(format(new Date(date.getTime())) as T)
}
let curDate = new Date(_nowDate.getTime())
const allDay = getCurMonthDayNum(curDate)
for (var i = 1; i <= getCurMonthDayNum(curDate); i++) {
curDate.setDate(i)
allDate.push(format(new Date(curDate.getTime())) as T)
}
let endDate = new Date(_nowDate.getTime())
endDate.setDate(allDay)
const endWeek = 7 - getWeek(endDate)
for (var i = 1; i <= endWeek; i++) {
const date = getNextMonthDay(endDate, i)
allDate.push(format(new Date(date.getTime())) as T)
}
// 至少6行
if (~~(allDate.length / 7) < 6) {
for (var i = endWeek + 1; i < endWeek + 1 + 7; i++) {
const date = getNextMonthDay(endDate, i)
allDate.push(format(new Date(date.getTime())) as T)
}
}
return allDate
}