How can I format a timestamp in Perl?

Brian picture Brian · Jan 27, 2010 · Viewed 50.3k times · Source

I would like to get this timestamps formatting:

01/13/2010 20:42:03 - -

Where it's always 2 digits for the number except for the year, where it's 4 digits. And it's based on a 24-hour clock.

How can I do this in Perl? I prefer native functions.

Answer

Sinan Ünür picture Sinan Ünür · Jan 27, 2010

POSIX provides strftime:

$ perl -MPOSIX -we 'print POSIX::strftime("%m/%d/%Y %H:%M:%S\n", localtime)'
01/27/2010 14:02:34

You might be tempted to write something like:

my ($sec, $min, $hr, $day, $mon, $year) = localtime;
printf("%02d/%02d/%04d %02d:%02d:%02d\n", 
       $day, $mon + 1, 1900 + $year, $hr, $min, $sec);

as a means of avoiding POSIX. Don't! AFAIK, POSIX.pm has been in the core since 1996 or 1997.