Question

I have a perl script that is getting the current time coming through in a but I am also looking to get the date 45 days prior to the current time as well. Here is what I have:

*already tried using date::calc DHMS which is why the second is formatted the way it is but it keeps returning an error

# get the current time stamp
use POSIX qw( strftime );
my $current_time = strftime("%Y-%m-%d %H:%M:%S", localtime);

print "\n$current_time\n";

# get the date 45 days ago
my $time = strftime("%Y, %m, %d, %H, %M, %S", localtime);

print "\n$time\n\n";
Was it helpful?

Solution

Preferably use DateTime, DateManip, or Date::Calc, but you can also:

use POSIX 'strftime', 'mktime';

my ($second,$minute,$hour,$day,$month,$year) = localtime();
my $time_45_days_ago = mktime($second,$minute,$hour,$day-45,$month,$year);
print strftime("%Y-%m-%d %H:%M:%S", localtime $time_45_days_ago), "\n";

OTHER TIPS

Have you tried DateTime?

my $now = DateTime->now( time_zone => 'local' );
my $a_while_ago = DateTime->now( time_zone => 'local' )->subtract( days => 45 );
print $a_while_ago->strftime("%Y, %m, %d, %H, %M, %S\n");
use DateTime;

my $now = DateTime->now( time_zone=>'local' );
my $then = $now->subtract( days => 45 );
print $then->strftime("%Y, %m, %d, %H, %M, %S");

Set the time_zone, it's important here.

Here's a simple solution using DateTime:

use strict;
use warnings;
use DateTime;

my $forty_five_days_ago = DateTime->now(time_zone=>"local")->subtract(days => 45);

my $output = $forty_five_days_ago->ymd(", ");

$output .= ", " . $forty_five_days_ago->hms(", ");

print "$output\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top