Is it possible to get/convert the mtime from fstat to local time in perl?
If I do
my $stat = stat($file);
my $mtime = $stat->mtime;
my $time = Time::Piece->strptime($time, '%s');
and then format that time to - say - '%Y%m%d%H%M'
I get a time that's 1 hour earlier than the time I see on ls -l
, as I live in and my machine is configured to GMT+1.
I would instead like to have an output that's consistent with ls -l
so that if
> ls -l foo.txt
> -rw-r--r--@ 1 somuser 296108113 163673 Mar 31 16:43 foo.txt
the output is 202003311643
instead of - like I get now - 202003311443
(GMT+1 and DST).
Is there a way to handle this in a straightforward way (i.e.: so that I don't have to manually adjust for the timezone, or DST)?
A Time::Piece object can represent either a local time or a UTC time. The following creates an object representing a UTC time:
my $time = Time::Piece->strptime($mtime, '%s');
The equivalent for creating a local time is
use Time::Piece;
my $time = localtime->strptime($mtime, '%s');
or
my $time = Time::Piece::localtime->strptime($mtime, '%s');
That said, using strptime
is unnecessary here. One can simply use
use Time::Piece;
my $time = localtime($mtime);
or
my $time = Time::Piece::localtime($mtime);
to get the correct Time::Piece object.