Substract 15 minutes using Perl

I thought it would be very simple, but I really have no options. I want to subtract 15 minutes from a specific time.

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

+4
source share
6 answers

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 
+18
source

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

 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) ); 
+5
source
 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

+2
source

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); 
+1
source

convert the time to unix time, for example, the current time: $unixtime = time(); , then subtract 15 * 60 from it, and then convert to a pretty 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); } 
+1
source

You can use the following routine if you are only concerned about the time not specified:

 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: It was an OP solution that he mentioned in the comments above the answer (in @eugene's answer).

0
source

All Articles