Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting localtime() in perl script

Tags:

date

perl

Wondering how to format the output of localtime() to year/month/day

I was able to do it easily using the 'date' command from terminal but I need to calculate previous dates as well, which I've figured out how to do in perl.

foreach my $i (0..7)
{
  my $date = localtime(time() - 60*60*24*$i);
  print "$i day(s) ago: $date\n";
}

Prints out this :

0 day(s) ago: Tue Apr  3 12:01:13 2012
1 day(s) ago: Mon Apr  2 12:01:13 2012
2 day(s) ago: Sun Apr  1 12:01:13 2012
3 day(s) ago: Sat Mar 31 12:01:13 2012
4 day(s) ago: Fri Mar 30 12:01:13 2012
5 day(s) ago: Thu Mar 29 12:01:13 2012
6 day(s) ago: Wed Mar 28 12:01:13 2012
7 day(s) ago: Tue Mar 27 12:01:13 2012
like image 467
jackie Avatar asked Dec 07 '25 08:12

jackie


2 Answers

Here's an example of POSIX::strftime:

use POSIX ();

my @local = ( localtime )[0..5];
foreach my $i ( 0..7 ) {
  my $date = POSIX::strftime( '%a %b %d %H:%M:%S %Y', @local);
  print "$i day(s) ago: $date\n";
  $local[3]--;
}
like image 166
Axeman Avatar answered Dec 08 '25 21:12

Axeman


If you are doing date math, use a module that does it right. For instance, DateTime:

use DateTime;

my $date = DateTime->now;

foreach my $i ( 0 .. 10 ) {
    $date->subtract( days => 1 );
    say $date->ymd( '/' );
    }
like image 27
brian d foy Avatar answered Dec 08 '25 20:12

brian d foy