How to calculate a date a week ago from today

前端 未结 4 1404
终归单人心
终归单人心 2021-01-13 09:08

I wanna calculate the date a week ago from today with a specific format and put it in to a variable. For example, today is Nov 21st. 2014, and I wanna print out

相关标签:
4条回答
  • 2021-01-13 09:31

    Why not just subtract X days from the "mday" field of localtime? This example shows subtracting 60 days from the end of august. I'm not sure who corrects the month but I think I'm getting the right 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
    
    0 讨论(0)
  • 2021-01-13 09:34

    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 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
    
    0 讨论(0)
  • 2021-01-13 09:44

    This is very simple using Date::Manip

        use Date::Manip;
        my $today = ParseDate("today");
        my $weeksago = DateCalc($today,"-7d");
    
    0 讨论(0)
  • 2021-01-13 09:51

    Check Time::Piece and Time::Seconds core modules,

    use Time::Piece;
    use Time::Seconds;
    
    my $t = localtime() - ONE_WEEK;
    print $t->ymd;
    

    output

    2014-11-14
    
    0 讨论(0)
提交回复
热议问题