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
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]--;
}
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( '/' );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With