有没有办法在 Perl 中使用 DateTime
计算出该月的第一天(最小日)和该月的最后一天(最大日)(给定月份作为输入)?
到目前为止,我弄清楚了如何传递第一个日期和最后一个日期来给我一个天数范围。
但我现在想做的只是传入一个月作为参数,例如 201203
并返回 min, maxday。
日期时间可以吗?
此外,我想将日期格式掩码从 YYYYMMDD 更改为 YYYY-MM-DD。
use strict;
use warnings;
use DateTime;
unless(@ARGV==2)
{
print "Usage: myperlscript first_date last_date\n";
exit(1);
}
my ($first_date,$last_date)=@ARGV;
my $date=DateTime->new(
{
year=>substr($first_date,0,4),
month=>substr($first_date,4,2),
day=>substr($first_date,6,2)
});
while($date->ymd('') le $last_date)
{
print $date->ymd('') . "\n";
#$date->add(days=>1); #every day
$date->add(days=>30);
}
预期结果:
2012-03-01
2012-03-31
最佳答案
DateTime为你做数学约会。您可以告诉ymd
要使用哪个字符作为分隔符:
use DateTime;
my( $year, $month ) = qw( 2012 2 );
my $date = DateTime->new(
year => $year,
month => $month,
day => 1,
);
my $date2 = $date->clone;
$date2->add( months => 1 )->subtract( days => 1 );
say $date->ymd('-');
say $date2->ymd('-');
"Last day of the month. Any shorter"中有很多例子在 Perlmonks 上,我通过谷歌搜索找到了它 "perl datetime last day of month" .
<小时/>这是一个 Time::Moment例子。它是 DateTime 的一个更精简、更快的子集:
use v5.10;
use Time::Moment;
my( $year, $month ) = qw( 2012 2 );
my $tm = Time::Moment->new(
year => $year,
month => $month,
day => 1,
);
my $tm2 = $tm->plus_months( 1 )->minus_days( 1 );
say $tm->strftime('%Y-%m-%d');
say $tm2->strftime('%Y-%m-%d');
关于perl - 如何使用 Perl 的 DateTime 获取该月的第一天和最后一天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9950193/