如何用Perl的DateTime得到本月的第一天和最后一天?

问题描述:

在perl中使用DateTime来计算月份的第一天(分钟日期)和月份的最后一天(max day),是否有方法计算该月份作为输入?如何用Perl的DateTime得到本月的第一天和最后一天?

到目前为止,我想出了如何在第一个日期,最后一个日期给我一个日期范围。

但是我现在要做的只是在一个月内作为参数传递,说201203并返回最小值,最大值。

这可能与DateTime?

此外,我想将日期格式掩码从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)[email protected]; 

    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 
+3

民主日总是1! – theglauber 2012-03-30 20:52:59

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的例子。这是日期时间的一个更精简,更快速的子集:

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'); 

第一天:

$dt->set_day(1); 

最后一天:

$dt->set_day(1)->add(months => 1)->subtract(days => 1); 
+8

如果你想避免改变'$ dt',不要忘记调用'clone'。 – ikegami 2012-03-30 20:50:45

作为替代有Perl核心模块Time::Piece

对于目前的月和年:

perl -MTime::Piece -wE '$t=localtime;say $t->month_last_day' 
31 

更一般地,是这样的:

use 5.010; 
use Time::Piece; 
my $MY = shift || die "Month and Year expected\n"; 
my $t = Time::Piece->strptime($MY, "%m%Y"); 
say $t->month_last_day; 

$ ./mycode 022012 
29 

令人惊讶的是,既不DateTime示例使用了特殊的构造last_day_of_month(布莱恩·d FOY的例子提供):

use DateTime; 
use strict; 
use 5.010; 

my($year, $month) = qw(2012 2); 

my $date = DateTime->new(
    year => $year, 
    month => $month, 
    day => 1, 
); 

my $date2 = DateTime->last_day_of_month( 
    year => $date->year, 
    month => $date->month, 
); 

say $date->ymd('-'); 
say $date2->ymd('-'); 

虽然日期时间类提供了一个构造函数来完成此操作,从现有DateTime对象获取月份的最后一天的最有效方法是请求对象计算它。该类公开了一个未记录的方法_month_length(),该方法非常高效地计算了月份的最后一天。有了您的DateTime对象调用$日期,你可以尝试

$date->_month_length($date->year,$date->month); 

这种方法是无证,因此它可能会或可能不会在您的日期时间版本支持。谨慎使用。