Skip to content

Instantly share code, notes, and snippets.

@usbharu
Created January 12, 2023 03:41
Show Gist options
  • Save usbharu/b72c5d4a50351c1cd5db59a82e04db8b to your computer and use it in GitHub Desktop.
Save usbharu/b72c5d4a50351c1cd5db59a82e04db8b to your computer and use it in GitHub Desktop.
日付操作.ts
export function nextMonth(date: Date, resetDate: boolean = false): Date {
return addOfMonthBy(date, 1, resetDate)
}
export function lastMonth(date: Date, resetDate: boolean = false): Date {
return subtractOfMonthBy(date, 1, resetDate)
}
export function lastYear(date: Date, resetMonth: boolean = false, resetDate: boolean = false): Date {
return subtractOfYearBy(date, 1, resetMonth, resetDate);
}
export function lastDayOfTheMonth(date: Date): Date {
const nextMonth1 = nextMonth(date, true);
nextMonth1.setDate(nextMonth1.getDate() - 1)
return nextMonth1
}
export function firstDayOfTheMonth(date: Date): Date {
const cloneDate = new Date(date);
cloneDate.setDate(1);
return cloneDate;
}
export function addOfMonthBy(date: Date, add: number, resetDate: boolean = false): Date {
const cloneDate = new Date(date);
if (resetDate) {
cloneDate.setDate(1)
}
cloneDate.setMonth(date.getMonth() + add);
return cloneDate;
}
export function subtractOfMonthBy(date: Date, subtract: number, resetDate: boolean = false): Date {
const cloneDate = new Date(date);
if (resetDate) {
cloneDate.setDate(1)
}
cloneDate.setMonth(date.getMonth() - subtract);
return cloneDate;
}
export function subtractOfYearBy(date: Date, subtract: number, resetMonth: boolean = false, resetDate: boolean = false): Date {
const cloneDate = new Date(date);
if (resetMonth) {
cloneDate.setMonth(0)
}
if (resetDate) {
cloneDate.setDate(1)
}
cloneDate.setFullYear(cloneDate.getFullYear() - subtract, cloneDate.getMonth(), cloneDate.getDate())
return cloneDate;
}
export function addOfYearBy(date: Date, add: number, resetMonth: boolean = false, resetDate: boolean = false): Date {
const cloneDate = new Date(date);
if (resetMonth) {
cloneDate.setMonth(0)
}
if (resetDate) {
cloneDate.setDate(1)
}
cloneDate.setFullYear(cloneDate.getFullYear() + add, cloneDate.getMonth(), cloneDate.getDate())
return cloneDate;
}
export function firstDayOfTheYear(date: Date): Date {
const cloneDate = new Date(date);
cloneDate.setFullYear(date.getFullYear(), 0, 1);
return cloneDate;
}
export function lastDayOfTheYear(date: Date, calculate: boolean = false): Date {
const cloneDate = new Date(date);
if (!calculate) {
cloneDate.setFullYear(date.getFullYear(), 11, 31)
return cloneDate;
}
const firstDayOfTheYear1 = firstDayOfTheYear(cloneDate);
firstDayOfTheYear1.setDate(-1)
return firstDayOfTheYear1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment