user3525290
user3525290

Reputation: 1619

Perl mojolicious datetime

I am trying to convert an array to a date

% use Time::Piece;
% my $now = localtime;
<%= $now->strftime("%b %e %Y %X") %><br>
Feb 2 2018 09:13:04 AM <- or current date and time
<%= $now->strftime('%Y%m%d', gmtime()) %>

prints 20180202

<%= $data->[1]->strftime('%Y%m%d', gmtime()) %>

Getting error

can't locate object method strftime via package "Feb 2 2018 09:13:04AM

% for my $data (@$query_data){
  $data->[1]
  $data->[2] etc...
%}

The Data prints just fine, but when I try to I guess convert I get the error.

my $myquery = "select date1, name, id from table where id=5;";

Data returned from the query is Feb 5 2018 08:15AM,Mike,5

push(@query, @{$dbh->$myquery)});
$c->stash(query_data => \@query);

Upvotes: 0

Views: 352

Answers (1)

Chris Turner
Chris Turner

Reputation: 8142

The problem is that you're doing a query to your database and one of the fields is being returned as a formatted date/time string. This isn't much use unless you're going to output it as is, so you need to parse it into a format that your code can use.

Time::Piece has a method for creating an object from a string called strptime which does the reverse of strftime that mimics the C function of the same name.

You need to go through each row in the results you get and parse that first field into the Time::Piece object the code in your template is expecting. I've not got any means of testing this, but I believe based on what code you've provided, that something like this should do the trick.

foreach my $row (@{$dbh->$myquery})
  {
  $row->[0]=Time::Piece->strptime($row->[0],"%b %e %Y %H:%M%p");
  push(@query, $row);
  }
$c->stash(query_data => \@query);

Upvotes: 1

Related Questions