Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a date a week ago from today

Tags:

perl

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: Last week is 2014-11-14.

I know we can use Date::Calc module, but I don't know how.

like image 364
NeilWang Avatar asked Nov 21 '14 07:11

NeilWang


People also ask

How do you calculate weeks from today's date?

To calculate the number of weeks between two dates, start by counting the number of days between the start and end date. Then, divide that number by 7 days per week.

How do I calculate days from today's date in Excel?

What'll you need to do is subtract today's date from the project start date. Excel has a TODAY function built in, which will save you from typing in the date in the correct format and continually updating as the days change. So, the formula is: =TODAY() – B2.


2 Answers

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
like image 144
mpapec Avatar answered Sep 30 '22 14:09

mpapec


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
like image 21
Samiron Avatar answered Sep 30 '22 13:09

Samiron