How to calculate date a week ago from today

I want to calculate a date a week ago from today in a specific format and put it in a variable. For example, today Nov 21st. 2014

, and I want to print: last week 2014-11-14

.

I know that we can use the module Date::Calc

, but I don’t know how.

+3


source to share


4 answers


Check Time::Piece

also the Time::Seconds

main modules,

use Time::Piece;
use Time::Seconds;

my $t = localtime() - ONE_WEEK;
print $t->ymd;

      



Output

2014-11-14

      

+7


source


DateTime version

use DateTime;
my $now = DateTime->now(time_zone => 'local')->subtract(weeks => 1);
print $now->ymd, ' ',$now->hms;

      

Date :: Calc version



Instead of one week, you can subtract 7 days using the Date :: Calc module

use Date::Calc qw(Add_Delta_Days);
my @date = Add_Delta_Days( 2014, 11, 21, -7 );
print join('-', @date);

OUTPUT
    2014-11-14

      

+2


source


Why not just subtract X days from the local time "mday" field? This example shows the subtraction of 60 days from the end of August. I'm not sure who is fixing the month, but I think I am getting the correct answer ...

$ date
Wed Aug 30 14:34:14 DFT 2017
$ perl -MPOSIX -e '@t=localtime time; $t[3] -= 60; print strftime( "%Y/%m/%d", @t), "\n";'
2017/07/01

      

+1


source


It's very easy using Date :: Manip

    use Date::Manip;
    my $today = ParseDate("today");
    my $weeksago = DateCalc($today,"-7d");

      

0


source







All Articles