Closed AyumuOgasawara closed 3 hours ago
以下のような形で、最初と最後の出費を取得した
// 出費の最初のデータと最後のデータを取得する
export const getFirstAndLastExpense = cache(
async (userId: string): Promise<getFirstAndLastExpenseResponse> => {
return await prisma.expense.aggregate({
where: {
userId: userId,
},
_min: {
date: true,
},
_max: {
date: true,
},
});
}
);
最初の月から最後の月までの間にある月を全て取得しようとしたら面白いことがわかった。 もしかしてこれがポインタですか?
初めに以下のように書いて実装していた
// minDateからmaxDateまでの月を取得
let currentDate = new Date(firstLastExpense._min.date.getFullYear(), firstLastExpense._min.date.getMonth(), 1);
const endDate = new Date(firstLastExpense._max.date.getFullYear(), firstLastExpense._max.date.getMonth(), 1);
console.log(currentDate);
while (currentDate <= endDate) {
const year = currentDate.getFullYear();
const month = (currentDate.getMonth());
monthsInRange.push(new Date(year, month));
// 次の月に移動
currentDate.setMonth(currentDate.getMonth() + 1);
}
するとうまく表示された。
2024-06-30T15:00:00.000Z
[
2024-06-30T15:00:00.000Z,
2024-07-31T15:00:00.000Z,
2024-08-31T15:00:00.000Z,
2024-09-30T15:00:00.000Z
]
以下のように書けると思ったので実装してみた
// minDateからmaxDateまでの月を取得
let currentDate = new Date(firstLastExpense._min.date.getFullYear(), firstLastExpense._min.date.getMonth(), 1);
const endDate = new Date(firstLastExpense._max.date.getFullYear(), firstLastExpense._max.date.getMonth(), 1);
while (currentDate <= endDate) {
console.log(currentDate);
monthsInRange.push(currentDate);
// 次の月に移動
currentDate.setMonth(currentDate.getMonth() + 1);
}
すると、whileの中のcurrentDateは思った通りに出力されているが、最終的には全て10-31に変更されている!?
2024-06-30T15:00:00.000Z
2024-07-31T15:00:00.000Z
2024-08-31T15:00:00.000Z
2024-09-30T15:00:00.000Z
[
2024-10-31T15:00:00.000Z,
2024-10-31T15:00:00.000Z,
2024-10-31T15:00:00.000Z,
2024-10-31T15:00:00.000Z
]
後々ドロップダウンなどで2024年6月
と示すなら2024-6
で取得したほうがいい。
const month = (currentDate.getMonth() + 1).toString();
2024-06
で取得する
const month = (currentDate.getMonth() + 1).toString().padStart(2, "0");
概要
DBからユーザーの最初の出費日と最後の出費日を取得し、以下のような形にする。 この理由より、以下の形にする。
monthsInRange = ["2024-9", "2024-10", "2024-11"]
親タスク
54
詳細タスク