7
6

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 5 years have passed since last update.

Perlで日付の差分を求める

Posted at

2つの DateTime オブジェクトから、その差を求める方法。
簡単に求まるかと思ったらちょっとハマったのでメモ。

DateTimeオブジェクトの使い方

まずは、モジュールの使い方を。

use strict;
use DateTime;

my $dt1 = DateTime->new(year => 2016, month => 9, day => 1);
my $dt2 = DateTime->today;

print "$dt1\n";   #=> 2016-09-01T00:00:00
print "$dt2\n";   #=> 2016-10-18T00:00:00

2つの日付の差

2つの日付の差の日数を求めたいので、 $dt2 から $dt1 を引き算してやる。
DateTimeオブジェクト同士の差は DateTime::Duration オブジェクトとして返ってくる。
上のコードの続きにこうやって書く。

my $duration = $dt2 - $dt1;
print $duration->delta_days . "\n";   #=> 17

ふむふm...!??
あれ? 17 って何??
1ヶ月どこ行った??

なぜこのようになるのか

というのは、DateTime::Durationの仕様のようで、

use Data::Dumper;
print Dumper($duration);

として、オブジェクトを確認してみると、

$VAR1 = bless( {
'seconds' => 0,
'minutes' => 0,
'end_of_month' => 'wrap',
'nanoseconds' => 0,
'days' => 17,
'months' => 1
}, 'DateTime::Duration' );

と、「1ヶ月と17日」という形で値を持っている。
1ヶ月が何日であるかは月によって異なるため、トータルで何日なのかを計算できないトノコト(すごい言い訳だ...)。

正しい日付差分の求め方

delta_days メソッドを使う!

my $delta = $dt2->delta_days($dt1);
print $delta->delta_days . "\n";   #=> 47

という感じで正しく差分の「47」日が得られる。

7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?