0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Day.jsの罠】diffで日数差がズレる原因と対策まとめ

Last updated at Posted at 2025-06-30

Day.jsの diff は時刻も含めて計算される罠

Day.jsで日付の差(日数や月数)を計算する際、diff を使うことが多いですが、時刻も考慮されるため、意図と違う値になることがあります。例えば「日数差を取りたいだけなのに、時刻がズレていて1日少なくなる」ことがあります。


❌ 時刻がずれていて差がずれる例

import dayjs from 'dayjs';

const start = dayjs('2025-01-01T00:00:00');
const end = dayjs('2025-01-10T23:59:00'); // ← 23:59

const diffDays = end.diff(start, 'day');
console.log(diffDays); // 結果: 8 ← ❌ 本当は9日あるように見えるのに…

.startOf('day') で時刻を揃えてから差分を取る

import dayjs from 'dayjs';

const start = dayjs('2025-01-01').startOf('day');
const end = dayjs('2025-01-10').startOf('day');

const diffDays = end.diff(start, 'day');
console.log(diffDays); // 結果: 9 ← ✅ 想定どおり

.endOf('day') を使って「含めたい」場合にも対応

const start = dayjs('2025-01-01').startOf('day');
const end = dayjs('2025-01-10').endOf('day');

const diffDays = end.diff(start, 'day'); 
console.log(diffDays); // 結果: 9 ← ✅ 最終日も含めた形で正しく出る

✅ ラップ関数にしておくと便利

const getPureDateDiff = (startDate: string, endDate: string): number => {
  const start = dayjs(startDate).startOf('day');
  const end = dayjs(endDate).startOf('day');
  return end.diff(start, 'day');
};

console.log(getPureDateDiff('2025-01-01', '2025-01-10')); // 9

✍️ まとめ

  • dayjs().diff() は「時刻も含めた差分」を返す。
  • 純粋な日付差(日数、月数など)を取りたい場合は、.startOf('day') を明示する。
  • 実装時は常に両方の時刻を揃える習慣をつけると、ズレを防げる。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?