2023-06-01 07:25:10 +00:00
|
|
|
/**
|
|
|
|
* A small wrapper around {@link Date} for convenience and additional
|
|
|
|
* functionality.
|
|
|
|
*/
|
2023-05-31 15:19:57 +00:00
|
|
|
export class DateWrapper {
|
2023-06-01 07:25:10 +00:00
|
|
|
/** The inner {@link Date}. */
|
2023-05-31 15:19:57 +00:00
|
|
|
public date: Date;
|
|
|
|
|
2023-06-01 07:25:10 +00:00
|
|
|
/** Create a new {@link DateWrapper} from a {@link Date} or string. */
|
2023-05-31 15:19:57 +00:00
|
|
|
constructor(date: Date | string) {
|
|
|
|
this.date = date instanceof Date ? date : new Date(date);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-06-01 07:25:10 +00:00
|
|
|
* Add the specified number of days to the inner date.
|
2023-05-31 15:19:57 +00:00
|
|
|
*
|
|
|
|
* @param days The amount of days to add, can also be negative to subtract.
|
|
|
|
*/
|
|
|
|
public addDays(days: number): void {
|
|
|
|
this.date.setDate(this.date.getDate() + days);
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Clone the current date and return a completely new DateWrapper. */
|
|
|
|
public clone(): DateWrapper {
|
|
|
|
return new DateWrapper(new Date(this.iso()));
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Get the day of the week with Monday starting as 1. */
|
|
|
|
public dayOfTheWeek(): number {
|
|
|
|
const day = this.date.getDay();
|
|
|
|
return day === 0 ? 7 : day;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Get the date as an ISO-formatted string. */
|
|
|
|
public iso(): string {
|
|
|
|
return this.date.toISOString();
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Get the day padded with a leading zero when necessary. */
|
|
|
|
public paddedDay(): string {
|
|
|
|
const day = this.date.getDate();
|
|
|
|
return day.toString().padStart(2, "0");
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Get the month padded with a leading zero when necessary. */
|
|
|
|
public paddedMonth(): string {
|
|
|
|
const month = this.date.getMonth() + 1;
|
|
|
|
return month.toString().padStart(2, "0");
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the week of the year the date is in.
|
|
|
|
*
|
|
|
|
* Code adapted from https://weeknumber.net/how-to/javascript.
|
|
|
|
* */
|
|
|
|
public week(): number {
|
|
|
|
const date = new Date(this.date.getTime());
|
|
|
|
date.setHours(0, 0, 0, 0);
|
|
|
|
|
|
|
|
// Thursday in the current week decides the year.
|
|
|
|
date.setDate(date.getDate() + 3 - ((date.getDay() + 6) % 7));
|
|
|
|
|
|
|
|
// January 4 is always in week 1.
|
|
|
|
const firstWeek = new Date(date.getFullYear(), 0, 4);
|
|
|
|
|
|
|
|
// Get the difference between the first week and the current date in days.
|
|
|
|
const dayDifference = (date.getTime() - firstWeek.getTime()) / 86_400_000;
|
|
|
|
|
2023-06-01 07:25:10 +00:00
|
|
|
// Adjust the day difference to Thursday.
|
|
|
|
const adjustedDays = dayDifference - 3 + ((firstWeek.getDay() + 6) % 7);
|
|
|
|
|
|
|
|
// Calculate the number of weeks from the amount of days in the difference.
|
|
|
|
return 1 + Math.round(adjustedDays / 7);
|
2023-05-31 15:19:57 +00:00
|
|
|
}
|
|
|
|
}
|