alig227
alig227

Reputation: 357

How to manipulate time in HH:MM format

I simply want to add 15 minute increments to a variable that holds data in HH:MM format in 24 hour clock mode.

I tried using Time:Piece which lets me format the time, but I'm not able to run conditions or manipulate the value since it forces me to use the strptime method. Is there a way around this?

In the code below, the condition fails because it is not able to read 00:45 from $start_time.

my $value = "00:15";
my $format = '%H:%M';
my $start_time = Time::Piece->strptime($value, $format);

print $start_time->strftime($format). "\n";

$start_time += 60 * 15;

print $start_time->strftime($format). "\n";

$start_time += 60 * 15;

print $start_time->strftime($format). "\n";

if ($start_time eq "00:45") {
    print "hello!\n";
}

Upvotes: 0

Views: 164

Answers (2)

alex
alex

Reputation: 1304

The most advanced module for date and time manipulation is a DateTime module:

use DateTime; 
my $t = DateTime->new( year=>0, hour=>0, minute=>0 ); 
for (1..10){ 
  print $t->strftime( "%H:%M\n" ); 
  $t = $t->add( minutes=>15 );
}

The module Date::Calc is very good too.

Upvotes: 1

ikegami
ikegami

Reputation: 385657

for my $h (0..23) {
   for my $m (0, 15, 30, 45) {
      push @times, sprintf("%02d:%02d", $h, $m);
   }
}

But using this, your schedule will be wrong twice a year if you inhabit somewhere with Daylight Saving Time.

Handling DST requires knowing the date and the timezone for which you are preparing the schedule.

Upvotes: 2

Related Questions