如何在Perl中使用Date :: Calc获取上个月的日期?

时间:2018-10-12 11:13:09

标签: perl

如何在perl中使用Date :: Calc获取上个月的日期?

例如,今天是8/2018-我希望该函数返回7/2018。

如果今天的日期是1/2019-它应该返回12/2018

3 个答案:

答案 0 :(得分:2)

请尝试以下代码

use Date::Calc qw(:all);

my ($current_year,$current_month,$current_day)=Today;

my ($result_year,$result_month,$result_day)=Add_Delta_YM($current_year,$current_month,$current_day,0,-1);

如果您需要完整的月份名称,请使用以下格式

my $result_month_name=Month_to_Text($result_month);

答案 1 :(得分:0)

Date :: Calc似乎使一切都变得比其复杂得多:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Date::Calc qw[Today Add_Delta_Days];

my @today = Today;

my ($year, $month) = Add_Delta_Days(@today, -$today[2]);

say "$month/$year";

我建议改用DateTime

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';

use DateTime;

my $today = DateTime->today;
$today->subtract(days => $today->day);
say $today->strftime('%m/%Y');

答案 2 :(得分:0)

Time::Moment也提供了一个不错的选择:

use strict;
use warnings;
use feature 'say';
use Time::Moment;

say Time::Moment->now->minus_months(1)->strftime('%m/%Y');