Converting epoch time into mm-dd-yyyy local date

6.4k Views Asked by At

so I am currently using

my $date = DateTime->now->mdy;

which gives me the format in "09-10-2013"

then i used

my $modTime = localtime((stat($some_file))[9]);

which gives me the date in format "Tue Sep 10 15:29:29 2013"

is there a way built in perl to format the $modTime to the format like $date? or do i have to do it manually?

thanks!

3

There are 3 best solutions below

0
On

Create a DateTime object using the from_epoch constructor.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use DateTime;

# Using $0 (the current file) in these examples.
my $epoch = (stat $0)[9];

my $dt = DateTime->from_epoch(epoch => $epoch);

say $dt->dmy;

Of course, that can be rewritten as a single line:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use DateTime;

say DateTime->from_epoch(epoch => (stat $0)[9])->dmy;

But for something this easy, I'd probably use Time::Piece (which is part of the Perl standard distribution) rather than DateTime.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

say localtime((stat $0)[9])->dmy;
0
On

Well, depending on what you mean by "manually", you can do it in a couple of short steps:

# demo.
# Put the whole local time/stat/etc in parentheses where I put localtime.
#
($m,$d,$y) = (localtime)[4,3,5];   # extract date fields using a list slice
$modtime = sprintf('%02d-%02d-%4d', $m+1, $d, $y+1900); # format the string

There's probably a way to do it in a single line, incorporating both the extraction and a more complex format string, but that would lead to unnecessary obfuscation.

-Tom Williams

0
On

Late to answer, already seen the good answer to use from_epoch (DateTime->from_epoch(epoch => $epoch);). You could also use POSIX's function strftime like: print strftime "%m-%d-%Y", localtime( ( stat $some_file )[9] );