Printing a Date

Problem

You need to print a date and time shown in Epoch seconds format in human-readable form.

Solution

Simply call localtime or gmtime in scalar context, which takes an Epoch second value and returns a string of the form Tue May 26 05:15:20 1998:

$STRING = localtime($EPOCH_SECONDS);

Alternatively, the strftime function in the standard POSIX module supports a more customizable output format, and takes individual DMYHMS values:

use POSIX qw(strftime);
$STRING = strftime($FORMAT, $SECONDS, $MINUTES, $HOUR,
                   $DAY_OF_MONTH, $MONTH, $YEAR, $WEEKDAY,
                   $YEARDAY, $DST);

The CPAN module Date::Manip has a UnixDate routine that works like a specialized form sprintf designed to handle dates. Pass it a Date::Manip date value. Using Date::Manip in lieu of POSIX::strftime has the advantage of not requiring a POSIX-compliant system.

use Date::Manip qw(UnixDate);
$STRING = UnixDate($DATE, $FORMAT);

Discussion

The simplest solution is built into Perl already: the localtime function. In scalar context, it returns the string formatted in a particular way:

               
                  Sun Sep 21 15:33:36 1997

This makes for simple code, although it restricts the format of the string:

use Time::Local;
$time = timelocal(50, 45, 3, 18, 0, 73);
print "Scalar localtime gives: ", scalar(localtime($time)), "\n";

                  Scalar localtime gives: Thu Jan 18 03:45:50 1973

Of course, localtime requires the date and time in Epoch seconds. The POSIX::strftime function takes a set of individual DMYMHS values and a format and returns a string. ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.