Reputation: 1320
I have the following one liner, this should convert the date from one week ago today to a readable format.
my $week_ago = strftime("%Y-%m-%d", time - 604800);
However I get the following error:
Usage: POSIX::strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)
Can anyone suggest what the issue is here? From my understanding, strftime
should convert a time stamp to a readable date.
Upvotes: 1
Views: 149
Reputation: 54381
As your error message says, POSIX's strftime
takes a list of vaules, not a unix timestamp. You need to call localtime
or gmtime
before you call it.
my $one_minute_ago = strftime("%Y-%m-%d", localtime(time - 60));
The above example is fine if you are doing date math with short amounts below one day. Everything above that is error-prone. For your one week ago scenario, use sobrique's answer instead.
Upvotes: 4
Reputation: 53508
Use Time::Piece
. It's a core module that replaces localtime
(and gmtime
) but turns it into a much more useful form.
use Time::Piece;
my $week_ago = localtime() - 604800;
print $week_ago -> strftime("%Y-%m-%d");
Note - both localtime
and gmtime
now return a Time::Piece
object, which means you can do numeric comparisons with it too.
You can also for clarity - import Time::Seconds
and use it to define more useful constants (like ONE_DAY
and ONE_WEEK
) as noted by Borodin in the comments.
use Time::Piece;
use Time::Seconds qw ( ONE_WEEK );
my $week_ago = localtime() - ONE_WEEK;
Upvotes: 4