84 lines
2.4 KiB
TypeScript
84 lines
2.4 KiB
TypeScript
/** 中国星期名称 */
|
||
const WEEKDAY_CN = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"] as const;
|
||
|
||
/** 中国时区 */
|
||
const TZ = "Asia/Shanghai";
|
||
|
||
/**
|
||
* 获取中国时区下的日期数字(月、日、星期)
|
||
*/
|
||
function getChinaDateParts(): { year: number; month: number; day: number; weekday: number } {
|
||
const now = new Date();
|
||
const formatter = new Intl.DateTimeFormat("en-CA", {
|
||
timeZone: TZ,
|
||
year: "numeric",
|
||
month: "numeric",
|
||
day: "numeric",
|
||
weekday: "short",
|
||
});
|
||
const parts = formatter.formatToParts(now);
|
||
const get = (type: string) => parseInt(parts.find((p) => p.type === type)?.value ?? "0", 10);
|
||
const weekdayStr = parts.find((p) => p.type === "weekday")?.value ?? "Sun";
|
||
const weekdayMap: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
|
||
return {
|
||
year: get("year"),
|
||
month: get("month"),
|
||
day: get("day"),
|
||
weekday: weekdayMap[weekdayStr] ?? 0,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 格式化为中文日期:M月D日 周X
|
||
*/
|
||
function formatDateCN(month: number, day: number, weekday: number): string {
|
||
return `${month}月${day}日 ${WEEKDAY_CN[weekday]}`;
|
||
}
|
||
|
||
/**
|
||
* 获取下一个周六、周日的日期(中国日历)
|
||
* session-1 对应周六,session-2 对应周日
|
||
*/
|
||
export function getNextWeekendDates(): { saturday: string; sunday: string } {
|
||
const { year, month, day, weekday } = getChinaDateParts();
|
||
|
||
let satM = month;
|
||
let satD = day;
|
||
let satW = 6;
|
||
let sunM = month;
|
||
let sunD = day;
|
||
let sunW = 0;
|
||
|
||
if (weekday === 0) {
|
||
// 今天周日:下周六 +6 天,下周日 +7 天
|
||
const d = new Date(year, month - 1, day);
|
||
d.setDate(d.getDate() + 6);
|
||
satM = d.getMonth() + 1;
|
||
satD = d.getDate();
|
||
d.setDate(d.getDate() + 1);
|
||
sunM = d.getMonth() + 1;
|
||
sunD = d.getDate();
|
||
} else if (weekday === 6) {
|
||
// 今天周六:明天周日
|
||
const d = new Date(year, month - 1, day);
|
||
d.setDate(d.getDate() + 1);
|
||
sunM = d.getMonth() + 1;
|
||
sunD = d.getDate();
|
||
} else {
|
||
// 周一至周五
|
||
const daysToSat = 6 - weekday;
|
||
const d = new Date(year, month - 1, day);
|
||
d.setDate(d.getDate() + daysToSat);
|
||
satM = d.getMonth() + 1;
|
||
satD = d.getDate();
|
||
d.setDate(d.getDate() + 1);
|
||
sunM = d.getMonth() + 1;
|
||
sunD = d.getDate();
|
||
}
|
||
|
||
return {
|
||
saturday: formatDateCN(satM, satD, 6),
|
||
sunday: formatDateCN(sunM, sunD, 0),
|
||
};
|
||
}
|