olivierg
olivierg

Reputation: 792

Perl convert time in localtime format to YYYYMMDD

I have a string containing a date with this format

my $time = 'Fri Jan  8 14:24:27 2016';

And i want to convert it to YYYYMMDD. I tried a couple of options such as :

use POSIX qw(strftime);
print strftime("%Y%m%d", $time);

But it won't work. Tried localtime($time) as well as many others but it won't work.

I guess i need to convert it to an intermediary format ?

Note : i need to use strftime/POSIX as i can't call other modules for many reasons. (no Date::Time etc.)

thanks in advance,

Upvotes: 3

Views: 1912

Answers (2)

Dave Cross
Dave Cross

Reputation: 69314

You're trying to use POSIX::strftime() incorrectly. It's always a good idea to check the documentation, which says this:

strftime

Convert date and time information to string. Returns the string.

Synopsis:

strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)

The month (mon), weekday (wday), and yearday (yday) begin at zero, i.e., January is 0, not 1; Sunday is 0, not 1; January 1st is 0, not 1. The year (year ) is given in years since 1900, i.e., the year 1995 is 95; the year 2001 is 101. Consult your system's strftime() manpage for details about these and the other arguments.

So passing it a string containing a random(ish) representation of a datetime was slightly optimistic.

You need to parse your string and extract the bits that you need to pass to strftime(). As you've already be shown, the Modern Perl way to do that is to use a module like Time::Piece. But it's perfectly possible to do it with standard Perl too.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';
use POSIX 'strftime';

my $time = 'Fri Jan  8 14:24:27 2016';

my ($day, $mon, $date, $hr, $min, $sec, $year) = split /[\s:]+/, $time;

my %months = (
  Jan => 0, Feb => 1, Mar => 2, Apr => 3,
  May => 4, Jun => 5, Jul => 6, Aug => 7,
  Sep => 8, Oct => 9, Nov => 10, Dec => 11,
);

$time = strftime('%Y%m%d',
                 $sec, $min, $hr, $date, $months{$mon}, $year - 1900);

say $time;

But don't do that. Use a module.

Upvotes: 1

choroba
choroba

Reputation: 242103

Use Time::Piece, part of the Perl core since 2007:

use Time::Piece;

my $time = 'Fri Jan  8 14:24:27 2016';
say Time::Piece->strptime($time, '%a %b %d %H:%M:%S %Y')->ymd("");

Upvotes: 4

Related Questions