Getting a date in Perl using time and localtime


3 lines of code to output the date in Perl. In this instance getting yesterdays date.

Firstly we get our time by calling the time function, which stores the number of seconds since the systems epoch time – normally 1st January 1970 UTC – If I want yestedays date I call the time function minus the number of seconds in the day, 24 * 60 * 60, multiply that by days in week, month, year etc.. to get other dates.

Next we call the localtime function which takes our time and converts it to a 9 element list to allow us to return day, month, year etc… so for my date I want the elements: 5 for year, 4 for month and 3 for the day.

So we have our date, the only thing we need to do now is format the string using the sprintf function, basically to give us a 2 digit figure for the month. Since perl starts its months at 0 we need to add +1 to the month number. Also we need to add +1900 to our year in order to make sure that we’re y2k compliant – the year element in our list normally returns the number of years since 1900, so 109 will be 2009 rather than taking the last 2 digits ’09’ which can be any year.

If you’ve not used sprintf basically its a function that formats any variable to a given pattern, also available in PHP and maybe a few other languages, anyway, the 3 lines of code are:

my $timeYesterday = time - 24 * 60 * 60;
my ($year, $month, $day) = (localtime($timeYesterday))[5,4,3];
my $date = sprintf ("%04d%02d%02d", $year+1900, $month+1, $day);

That returns 20090720, if I want hyphens in there then I can do:

my $date = sprintf ("%04d-%02d-%02d", $year+1900, $month+1, $day);

That returns 2009-07-20, and if I want a 2 digit year then I can do:

my $date = sprintf ("%02d-%02d-%02d", $year+1900, $month+1, $day);

Which returns 09-07-20

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>