slicks1 slicks1 - 5 months ago 7
Perl Question

issue with date formatting perl

I have the following code:

$epoc = $rs->{'lastlogin'};
$date = localtime($epoc);


lastlogin
is a
unix timestamp
.

The output is as follows:
Tue Jul 5 13:46:43 2016


What I'm looking for is
Tue Jul 5 2016 13:46:43


As you can see the year is moved to the left one position.

I am also a newbie so i tried a few matches from here: date and time functions in perl but could not find a match for date formatting from a unix timestamp.

Answer

The core Time::Piece overloads the built-in localtime function so that it returns an object with an strftime method, allowing you to format the result as your wish

(localtime cotinues to perform in the same way for all other operations, so you are not losing any functionality)

use strict;
use warnings 'all';

use Time::Piece;

my $rs = { lastlogin => 1467726403 };

my $epoc = $rs->{lastlogin};
my $date = localtime($epoc)->strftime('%a %b %d %Y %H:%M:%S');

print $date, "\n";

output

Tue Jul 05 2016 14:46:43



To change the time to 12-hour, you ned to use the %I format specifier for the hours instead of %H, and add %P at the end to provide AM or PM

my $date = localtime($epoc)->strftime('%a %b %d %Y %I:%M:%S %p');

output

Tue Jul 05 2016 02:46:43 PM