0

I have a task in perl in which I need to execute 'some_code' but only if date is older than 24 hours counting from now. I'm trying the below code but it doesn't seems to be working.

sub function {

  use Date::Manip::Date
  use Date::Parse
  use Date::Format;

  my $yesterday = time() - 60*60*24;
  my $x = shift;
  my $env = shift;

  $env->{some_code} = 1 if $x < $yesterday;

 return $x;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 3
    Please provide example `$x` value, actual output and expected output. – January Oct 18 '12 at 14:23
  • 2
    `use`-ing the modules is not enough, these modules provide functions which you must apply to perform the date calculations. – Joel Berger Oct 18 '12 at 14:40
  • 1
    What kinds of values can `$x` have? Where do you get them from before you call the function? Are they Unix time values (seconds since 1970) like the return value of `time()`? – gpvos Oct 18 '12 at 14:43

2 Answers2

1

You can do it easily, only using core functions.

#!/usr/bin/perl                                                                                   

use strict;

my $new_time   = 1350570164; # 2012-10-18 14:22:44
my $older_time = 1350450164; # 2012-10-17 05:02:44

printf "time in sec: %d older that 24 hours: %d\n", $new_time, is_time_older_24($new_time);
printf "time in sec: %d older than 24 hours: %d\n", $older_time, is_time_older_24($older_time);

sub is_time_older_24 {
    my $given_time = shift;

    my $yesterday_time = time() - 60 * 60 * 24;
    return $given_time <= $yesterday_time
            ? 1
            : 0;
}

Output:

time in sec: 1350570164 older that 24 hours: 0
time in sec: 1350450164 older than 24 hours: 1
Pavel Vlasov
  • 3,455
  • 21
  • 21
  • 1
    This works generally, but is not exact. Using the Date/Time modules accounts for things like leap seconds, etc. If "close" is good enough, then this is fine, if you need precision, use a module. – Joel Berger Oct 18 '12 at 14:38
  • @Joel Berger, that was my first thought too, but the specs call for 24 hours, not one day. – ikegami Oct 18 '12 at 14:57
  • @ikegami in a mission-critical situation I think I would still rather trust that to a module, however, yeah, 24 hours is generally easier than a day. – Joel Berger Oct 18 '12 at 15:03
1
#! /usr/bin/env perl
use Modern::Perl;
use Data::Dumper;
use DateTime;

my $now = DateTime->new( 
                    year => 2012, month => 10, day => 18, 
                    hour => 17, minute => 30, 
                    time_zone => 'UTC'
                );
# my $now = DateTime->now(time_zone => 'UTC');

my $last_run = DateTime->new(
                    year => 2012, month => 10, day => 17, 
                    hour => 19, minute => 30, 
                    time_zone => 'UTC'
                );

my $duration= $now->subtract_datetime($last_run);
say "hours: " . $duration->hours;

Result:

hours: 22

see also:

fanlim
  • 300
  • 4
  • 11