Quickly getting to YYYY-mm-dd HH:MM:SS in Perl
Solution 1:
Use strftime
in the standard POSIX
module. The arguments to strftime
in Perl’s binding were designed to align with the return values from localtime
and gmtime
. Compare
strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)
with
my ($sec,$min,$hour,$mday,$mon,$year,$wday, $yday, $isdst) = gmtime(time);
Example command-line use is
$ perl -MPOSIX -le 'print strftime "%F %T", localtime $^T'
or from a source file as in
use POSIX;
print strftime "%F %T", localtime time;
Some systems do not support the %F
and %T
shorthands, so you will have to be explicit with
print strftime "%Y-%m-%d %H:%M:%S", localtime time;
or
print strftime "%Y-%m-%d %H:%M:%S", gmtime time;
Note that time
returns the current time when called whereas $^T
is fixed to the time when your program started. With gmtime
, the return value is the current time in GMT. Retrieve time in your local timezone with localtime
.
Solution 2:
Why not use the DateTime
module to do the dirty work for you? It's easy to write and remember!
use strict;
use warnings;
use DateTime;
my $dt = DateTime->now; # Stores current date and time as datetime object
my $date = $dt->ymd; # Retrieves date as a string in 'yyyy-mm-dd' format
my $time = $dt->hms; # Retrieves time as a string in 'hh:mm:ss' format
my $wanted = "$date $time"; # creates 'yyyy-mm-dd hh:mm:ss' string
print $wanted;
Once you know what's going on, you can get rid of the temps and save a few lines of code:
use strict;
use warnings;
use DateTime;
my $dt = DateTime->now;
print join ' ', $dt->ymd, $dt->hms;
Solution 3:
Try this:
use POSIX qw/strftime/;
print strftime('%Y-%m-%d',localtime);
the strftime
method does the job effectively for me. Very simple and efficient.