2
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?

More than 3 years have passed since last update.

date-fns の differenceInDays を気軽に使うとハマる件

Posted at

気をつけましょう…

ハマり点その1

console.log( differenceInDays(new Date(1951, 4, 7), new Date(1951, 4, 8)) );
console.log( differenceInDays(new Date(1951, 4, 6), new Date(1951, 4, 7)) );
console.log( differenceInDays(new Date(1951, 4, 5), new Date(1951, 4, 6)) );

-1
0   👈
-1

これは1951年5月6日が夏時間開始日で23時間しかなかったから、
というわけでUTCで計算すれば

console.log( differenceInDays(Date.UTC(1951, 4, 7), Date.UTC(1951, 4, 8)) );
console.log( differenceInDays(Date.UTC(1951, 4, 6), Date.UTC(1951, 4, 7)) );
console.log( differenceInDays(Date.UTC(1951, 4, 5), Date.UTC(1951, 4, 6)) );

-1
-1
-1

OK。

ハマり点その2

console.log( differenceInDays(Date.UTC(1951, 8, 10), Date.UTC(1958, 6, 1)), (Date.UTC(1951, 8, 10) - Date.UTC(1958 ,6, 1)) / 86400000 );
console.log( differenceInDays(Date.UTC(1951, 8,  9), Date.UTC(1958, 6, 1)), (Date.UTC(1951, 8,  9) - Date.UTC(1975, 6,1 )) / 86400000 );
console.log( differenceInDays(Date.UTC(1951, 8,  8), Date.UTC(1958, 6, 1)), (Date.UTC(1951, 8,  8) - Date.UTC(1975, 6,1 )) / 86400000 );
console.log( differenceInDays(Date.UTC(1951, 8,  7), Date.UTC(1958, 6, 1)), (Date.UTC(1951, 8,  7) - Date.UTC(1975, 6,1 )) / 86400000 );
console.log( differenceInDays(Date.UTC(1951, 8,  6), Date.UTC(1958, 6, 1)), (Date.UTC(1951, 8,  6) - Date.UTC(1975, 6,1 )) / 86400000 );

-2486 -2486
-2487 -2487
-2487 -2488  👈
-2488 -2489  👈
-2489 -2490  👈

!?
(ちなみにこの1951年9月8日は平和条約が締結された日ですが、関係あるのだろうか?)

2
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
2
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?