The Man
The Man

Reputation: 101

Substract 15 Minutes from time using Perl

I thought this was going to be very simple but I am really out of options now. I want to substract 15 minutes from a given time.

Example My time is 15:04 I want to substract 15 minutes to be 14:49. I have searched for solutions on the internet but there is no perl module that can help me out.

Upvotes: 9

Views: 23573

Answers (6)

Sandeep
Sandeep

Reputation: 1532

You can use the below sub-routine if you are only concerned about time not date:

sub subTime{
    my ($time) = @_;
    my @splittime = split(':', $time);
    my $hour = $splittime[0];
    my $min = $splittime[1];
    if($min < 15){
        $min=($min+60)-15; 
        $hour-=1;
    }
    else{
        $min = $min-15;
    } 
    return "$hour:$min";
} 

Disclamer: This was the solution OP used, he mentioned it in comments in above answer (in @eugene's answer).

Upvotes: 0

Sodved
Sodved

Reputation: 8588

Well it all depends on how your time is stored. I prefer to use a time_t as returned by the time built in.

my $now = time();
my $before1 = $now - (15*60);      # 15 minutes ago
my $before2 = $now - (3*60*60);    # 3 hours ago
my $before3 = $now - (2*24*60*60); # 2 days ago

For output I use the POSIX module

print POSIX::strftime( '%Y-%m-%d %T', localtime($before1) );

Upvotes: 7

bob.faist
bob.faist

Reputation: 728

perl -MClass::Date -e 'my $d=Class::Date->new("2011-07-13 15:04:00"); my $d2 = $d-"15m"; print $d2, "\n";'

Output:

2011-07-13 14:49:00

Upvotes: 2

Eugene Yarmash
Eugene Yarmash

Reputation: 149823

You can use DateTime:

my $dt = DateTime->new(
    year   => 1,
    month  => 1,
    day    => 1,
    hour   => 15, 
    minute => 4,
);  

$dt->subtract(minutes => 15);
printf "%d:%d\n", $dt->hour, $dt->minute; # prints 14:49

Upvotes: 23

atlau
atlau

Reputation: 971

convert the time to unix time, for example the current time: $unixtime = time(); then subtract 15*60 from it then convert to a nice string with something like

sub display_time {
  my ($sec,$min,$hour,$mday,$mon,$year,undef,undef,undef) = localtime(time);
  $year += 1900;
  $mon += 1;
  return "$year.".sprintf("%02d.%02d %02d:%02d:%02d",$mon,$mday,$hour,$min,$sec);
}

Upvotes: 1

Aziz Shaikh
Aziz Shaikh

Reputation: 16524

Try using Date::Calc

use Date::Calc qw(Add_Delta_DHMS); 

($year2, $month2, $day2, $h2, $m2, $s2) = 
Add_Delta_DHMS( $year, $month, $day, $hour, $minute, $second, $days_offset, $hour_offset, $minute_offset, $second_offset );

($y,$m,$d,$H,$M,$S) = Add_Delta_DHMS(Today_and_Now(), 0, 0, -15, 0);

Upvotes: 1

Related Questions