且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何计算 Perl 中两个日期之间的天数?

更新时间:2023-01-31 16:14:36

这似乎有点混乱,因为根据您要完成的任务,两个日期之间的天数"可能意味着至少两件不同的事情:

There seems to be quite a bit of confusion because, depending on what you are trying to accomplish, "the number of days between two dates" can mean at least two different things:

  1. 两个日期之间的日历距离.
  2. 两个日期之间的绝对距离.

作为示例并注意区别,假设您有两个构造如下的 DateTime 对象:

As an example and to note the difference, assume that you have two DateTime objects constructed as follows:

use DateTime;

sub iso8601_date {
  die unless $_[0] =~ m/^(dddd)-(dd)-(dd)T(dd):(dd):(dd)Z$/;
  return DateTime->new(year => $1, month => $2, day => $3,
    hour => $4, minute => $5, second => $6, time_zone  => 'UTC');
}

my $dt1 = iso8601_date('2014-11-04T23:35:42Z');
my $dt2 = iso8601_date('2014-11-07T01:15:18Z');

请注意,$dt1 在周二很晚,而 $dt2 在下周五 非常.

Note that $dt1 is quite late on a Tuesday, while $dt2 is very early on the following Friday.

如果您想要日历距离,请使用:

If you want the calendar distance use:

my $days = $dt2->delta_days($dt1)->delta_days();
print "$days
" # -> 3

确实,周二和周五之间有3天.日历距离 1 表示明天",距离 -1 表示昨天".DateTime 对象的时间"部分几乎不相关(除非两个日期位于不同的时区,否则您必须决定这两个日期之间的日历距离"应该是什么意思).

Indeed, between, Tuesday and Friday there are 3 days. A calendar distance of 1 means "tomorrow" and a distance of -1 means "yesterday". The "time" part of the DateTime objects is mostly irrelevant (except perhaps if the two dates fall on different time zones, then you would have to decide what "the calendar distance" between those two dates should mean).

如果您想要绝对距离,请改用:

If you want the absolute distance then instead use:

my $days = $dt2->subtract_datetime_absolute($dt1)->delta_seconds / (24*60*60);
print "$days
"; # -> 2.06916666666667

事实上,如果你想以 24 小时为单位分割两个日期之间的时间,它们之间只有大约 2.07 天.根据您的应用程序,您可能希望截断或舍入此数字.DateTime 对象的时间"部分非常相关,即使对于不同时区的日期也能很好地定义预期结果.

Indeed, if you want to split the time between the two dates in 24-hour chunks, there are only about 2.07 days between them. Depending on your application, you might want to truncate or round this number. The "time" part of the DateTime objects is very relevant, and the expected result is well defined even for dates on different time zones.