I am parsing data and getting a date. I then convert that to iso8601 object. However I am stuck trying to get just the year month date format.
use DateTime::Format::ISO8601;
use POSIX qw(strftime);
my $dt_str = 'Frank_Gibson.20180703T230600.Program_Manager.New_York.doc';
my @perl_time_array = split /\./, $dt_str;
my $dt = DateTime::Format::ISO8601->parse_datetime($perl_time_array[1]);
prints 2018-07-03T23:06:00
How do I get just the date? I have tried to use
$dt = strftime('%Y-%m-%d',$dt);
But I am getting the following error.
Usage: POSIX::strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1) at /home/pi/code/perl/perl_regex_lookahead.pl line 26.
Do I just use a regex to get what I am looking for or is there a way to format using using DateTime::Format::ISO8601
or strftime
There are two subroutines called strftime()
here and I think that's slightly confusing you.
You are (accidentally?) calling the strftime()
function from the POSIX
module and, as your error message tells you, that subroutine expects very specific arguments (basically the list of values you get back from localtime()
or gmtime()
).
But you don't need to do that. Your $dt
variable is an object of the class DateTime
. And DateTime
objects have their own strftime()
method that you can call on the object.
$dt->strftime('%Y-%m-%d'); # 2018-07-03
It's also worth mentioning that the strftime()
method is really only intended for creating strings in more obscure date and time formats. For common formats, the DateTime
class has other methods that you can use. For example, the date format that you want can be produced using the ymd()
method.
$dt->ymd; # 2018-07-03
This all means that you can remove the use POSIX
line from your code. You won't be using that module at all. Everything you need is in the DateTime
class.