1

I would like to convert 2003-07-04T15:56:00 to 04/07-2003 so I do

#!/usr/bin/perl -w
use strict;
use Date::Format;
use Data::Dumper;

my $time_format = "%d/%m-%Y";
my $time = "2003-07-04T15:56:00";

print Dumper time2str($time_format, $time);

and get

Argument "2003-07-04T15:56:00" isn't numeric in localtime at /usr/lib/perl5/vendor_perl/5.8.8/Date/Format.pm line 123.
$VAR1 = '01/01-1970';

Any idea how to do this date convertion?

Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162

2 Answers2

3

The error message is spot on: time2str expects a numeric date representation, but got the string "2003-07-04T15:56:00".

There are most likely several ways to resolve this. One of them is Time::Local, that can help you create a proper numeric date.

Try to replace

my $time = "2003-07-04T15:56:00";

with:

my $time = timelocal(0,56,15,4,7-1,2003);

As @Jorik pointed out, month specification is a little unusual:

It is worth drawing particular attention to the expected ranges for the values provided. The value for the day of the month is the actual day (ie 1..31), while the month is the number of months since January (0..11). This is consistent with the values returned from localtime() and gmtime().

Edit For generic solutions to dates in strings check out the answers to this question: How can I parse dates and convert time zones in Perl?.

Community
  • 1
  • 1
Anders Lindahl
  • 41,582
  • 9
  • 89
  • 93
  • 1
    Small but significant comment (1 month ;). The original string probably refers to the 4th of July, whereas the arguments to timelocal would refer to the 4th of August (0..11)! – Jorik May 27 '11 at 11:23
  • The thing is, that get the dates in `2003-07-04T15:56:00` format, so should I just regex to get it to `dd/mm-yyyy` or does there exist a way to this for me? – Sandra Schlichting May 27 '11 at 11:32
  • Sandra: There are several solutions to that aswell, I've updated the answer with a link to an earlier question about this. – Anders Lindahl May 27 '11 at 11:40
2
DateTime::Format::Strptime
    ->new(pattern => '%FT%T')
    ->parse_datetime('2003-07-04T15:56:00')
    ->strftime('%d/%m-%Y')

# returns 04/07-2003
daxim
  • 39,270
  • 4
  • 65
  • 132