Home > database >  How to get timestamp and do maths on it without caring about the day?
How to get timestamp and do maths on it without caring about the day?

Time:08-17

I am trying to do some maths with timestamps (or rather without timestamps, but I think I need to use timestamps) in Perl, which is not a language I am very familiar with. I'm particularly unfamiliar with date an time functions of it.

Basically I have a function that takes 5 integers as arguments.

sub calculateEndTime {
    my ($hour, $minute, $second, $roundingInterval ,$buffer)
    ...
}

The maths I want to do is probably irrelevant but is simply:

  1. Round the minutes to the nearest $roundingInterval. E.g if it's 15, round to the nearest quarter hour. I used the below to do it.
    my $nearestInterval = round($minute / $roundingInterval) * $roundingInterval;
    $hour = $hour   1 if $nearestInterval == 60; #That's gonna screw up future calculations
    $nearestInterval = 0 if $nearestInterval == 60;
  1. If the given hour, minute, second is within $buffer minutes (default 5 minutes) either side of the rounded time, return the initial ($hour, $minute, $second).

This is where it kind of fell apart, I need a timestamp to check this, manually is going to be a pain to check if hours tick over etc. So how do I create a timestamp from just an hour, minute and second when I don't care about the date? Just give it the current date or some other placeholder?

CodePudding user response:

Work with just seconds. Then all you need is

my $rounded = round( $time / $internal ) * $interval;

if ( abs( $rounded - $time ) < $buffer ) {
   $rounded = $time;
}

sub to_time {
   my $hours   = shift;
   my $minutes = shift;
   my $seconds = shift;

   my $time = ( $hour * 60   $minutes ) * 60   $seconds;

   return $time;
}

sub from_time {
   my $time = shift;

   my $seconds = $time % 60;  $time = ( $time - $seconds ) / 60;
   my $minutes = $time % 60;  $time = ( $time - $minutes ) / 60;
   my $hours   = $time;

   return ( $hours, $minutes, $seconds );
}

sub calculate_end_time {
   my ( $hours, $minutes, $seconds, $interval, $buffer ) = @_;

   my $time = to_time( $hours, $minutes, $seconds );

   $interval *= 60;
   $buffer   *= 60;

   my $rounded = round( $time / $internal ) * $interval;

   if ( abs( $rounded - $time ) < $buffer ) {
      $rounded = $time;
   }

   return from_time( $rounded );
}
  •  Tags:  
  • perl
  • Related