Skip to content

Instantly share code, notes, and snippets.

@naosim
Created March 23, 2023 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naosim/6add88711b6d4029903863d334f6e087 to your computer and use it in GitHub Desktop.
Save naosim/6add88711b6d4029903863d334f6e087 to your computer and use it in GitHub Desktop.
日付を返す関数。AIが書いたので意図通り動くかわかりません。
function parseDateString(dateStr, holidays) {
let date;
if (/^\d{4}\/\d{1,2}\/\d{1,2}$/.test(dateStr)) {
// 日付指定の場合
date = new Date(dateStr);
} else if (/^FY\d{2}\/\dQ$/.test(dateStr)) {
// 年度・四半期指定の場合
const fy = parseInt(dateStr.slice(2, 4), 10);
const q = parseInt(dateStr.slice(-2, -1), 10);
const year = 2000 + fy + (q === 1 ? 0 : 1);
const month = (q - 1) * 3 + 1;
date = new Date(year, month - 1, 1);
} else if (/^\d{4}\/\d{1,2}\/上旬$/.test(dateStr)) {
// 上旬指定の場合
const year = parseInt(dateStr.slice(0, 4), 10);
const month = parseInt(dateStr.slice(5, 7), 10);
date = new Date(year, month - 1, 1);
if (month === 12) {
date.setFullYear(year + 1);
date.setMonth(0);
} else {
date.setMonth(month);
}
date.setDate(5);
} else if (/^\d{4}\/\d{1,2}\/中旬$/.test(dateStr)) {
// 中旬指定の場合
const year = parseInt(dateStr.slice(0, 4), 10);
const month = parseInt(dateStr.slice(5, 7), 10);
date = new Date(year, month - 1, 15);
} else if (/^\d{4}\/\d{1,2}\/末$/.test(dateStr)) {
// 末指定の場合
const year = parseInt(dateStr.slice(0, 4), 10);
const month = parseInt(dateStr.slice(5, 7), 10);
date = new Date(year, month, 0);
} else {
throw new Error("Invalid date string");
}
// 土日祝日を考慮して日付を修正する
while ([0, 6].includes(date.getDay()) || holidays.some(h => h.getTime() === date.getTime())) {
date.setDate(date.getDate() - 1);
}
return date;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment