views:

1856

answers:

2

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.

+10  A: 

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.

Sinan Ünür
Judging from the unambiguous `01/13/2010` in the question, Brian seems to want a format of `"%m/%d/...` or even `"%D %T"`.
Greg Bacon
@gbacon `%D %T` did not work on `perl` 5.10.1 on Windows (it did on Linux), I decided to play safe. Thanks for noticing that I accidentally swapped `%m` and `%d`.
Sinan Ünür
Argh! Good catch, and good to remember.
Greg Bacon
But don't avoid learning about `localtime` (or `sprintf`) either.
mobrule
+1  A: 

Try Date::Format

Diego Dias