Thursday, June 29, 2017

Perl : How to obtain a past date in YYYY-MM-DD format

In one particular perl script, I wanted to obtain the date that was 30 days ago, in YYYY-MM-DD format.  Here is the perl code I wrote.

#!/usr/bin/perl
use strict;
use warnings;

# 1 day = 86400 seconds
# 30 days 2592000 seconds

my ($day, $month, $year) = (localtime(time() - 2592000))[3,4,5];
$month++;
$year += 1900;
print "$year-$month-$day \n";

__END__



Perl's built-in function time returns the number of seconds since the epoch.  The epoch is 00:00:00 UTC, January 1, 1970.
If we subtract 2592000 from the value returned by time, the result we get is useful for obtaining a date from 30 days ago.

Using the value obtained from time function, Perl's built-in function localtime is useful in obtaining day of month, month, and year.
Value of year returned by localtime function contains the number of years since 1900.  So we have to add 1900 to it, to obtain the year we were looking for.
Value of month returned by localtime function is in the range 0 to 11, representing January to December.  So adding 1 to it gives the month of year that we are interested in.

No comments:

Post a Comment