3

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";
jordanm
  • 33,009
  • 7
  • 61
  • 76

4 Answers4

6

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");
gpojd
  • 22,558
  • 8
  • 42
  • 71
5

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";
ysth
  • 96,171
  • 6
  • 121
  • 214
  • In my opinion this solution is harder to read, especially for the person who do the maintenance. I would prefer DateTime's substract. But if no DateTime module is available... – fanlim Jan 06 '13 at 13:22
3
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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
alex
  • 1,304
  • 12
  • 15
2

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";
  • 2
    `$output = $forty_five_days_ago->strftime("%Y, %m, %d, %H, %M, %S");` would also do the trick. – ikegami Jan 03 '13 at 23:04