Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert localtime into YYYY-MM-DD with Perl

Tags:

perl

I have this code which obtains the most recent coming friday, no matter what the current date is:

for(my $i = 1; $i < 8; $i++) {
     my $t = time() + $i * 24 * 3600;
     next unless (localtime($t))[6] == 5; # friday                                                                                               
     $nextfri = scalar(localtime($t));                                                                                                           
     last;                                                                                                                                        
}

This returns the date in the format: Fri May 11 13:47:24 2018

However, II must use this date for a SQL query, and so I must have this date in this format: YYYY-MM-DD

I have tried using Time::Piece:

 print STDERR "Time::Piece: " . Time::Piece->strptime("$nextfri", '%Y %m %d'), "\n";

But I receive this error: Error parsing time at /usr/local/lib/perl/5.18.2/Time/Piece.pm line 481, <DATA> line 1.

How do I change the format of the date?

like image 394
Jonathan Dewein Avatar asked Jan 24 '26 13:01

Jonathan Dewein


1 Answers

Use POSIX::strftime to convert localtime parts to a formatted string.

use strict;
use warnings;

use POSIX qw{strftime};

my $nextfri;
for (my $i = 1; $i < 8; $i++) {
  my @t = localtime(time() + $i * 24 * 3600);
  next unless $t[6] == 5; # friday
  $nextfri = strftime '%Y %m %d', @t;
  last;
}

But I would suggest you use a library like DateTime instead because the above code can lead to incorrect results because of its incorrect assumption that every day has 24 hours.

use strict;
use warnings;

use DateTime;

my $nextfri = DateTime->now;
do {
  $nextfri->add(days => 1);
} until ($nextfri->day_of_week == 5);

print $nextfri->ymd(' '); # or '-'
like image 85
mwp Avatar answered Jan 29 '26 03:01

mwp