Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

How to get quick i nice date format?

by uksza (Canon)
on Feb 08, 2006 at 10:24 UTC ( #528767=perlquestion: print w/replies, xml ) Need Help??

uksza has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks

I need sometimes in my litte scripts date/time in nice format. I can use (on Linux machines):
my $date = `date +%Y-%m-%d_%H:%M`; chomp $data;
my ( $ss, $mm, $hh, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(); my $data = sprintf( "%d-%02d-%02d %02d:%02d", ( $year += 1900, $mon += 1, $mday, $hh, $mm ) );
use POSIX 'strftime'; my $date = strftime '%x %X.', localtime;
First is little and nice, but use external program.
Second pure Perl, but a little to long...
Third is almost OK, but is it good idea to use POSIX in 20 lines scripts?
In dates and times I can't found nothing else

How do you do this in your's programs?

greetz, Uksza

Yes, smart people know that fat arrow autoquotes the left argument. But why should you require your code to be maintained by smart people?
Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: How to get quick i nice date format?
by demerphq (Chancellor) on Feb 08, 2006 at 10:47 UTC

    You want to be careful with strftime format strings if you want your code to be portable. Only a minimal set is truely portable. Anyway, here is what I would and do use.

    sub iso_time { require POSIX; POSIX::strftime("%Y-%m-%d %H:%M:%S", localtime( shift( @_ ) || time ) ); }

Re: How to get quick i nice date format?
by holli (Abbot) on Feb 08, 2006 at 12:08 UTC is in the core (afaik), so there is no harm whatsoever in using it.

    holli, /regexed monk/
Re: How to get quick i nice date format?
by davis (Vicar) on Feb 08, 2006 at 10:36 UTC
    You can try localtime in scalar context:
    my $nowthen = localtime; print $nowthen, "\n";
    Update: wow, I completely missed that you're trying to display a date in ISO 8601 format. demerphq's solution is better.

    Kids, you tried your hardest, and you failed miserably. The lesson is: Never try.
Re: How to get quick i nice date format?
by mickeyn (Priest) on Feb 08, 2006 at 15:30 UTC
    you may also want to take a look at Time::Format, it extends the that was suggested.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://528767]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2020-10-19 21:44 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (207 votes). Check out past polls.