Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Generating basic time intervals between two times

by jorg (Friar)
on May 20, 2001 at 15:26 UTC ( [id://81819]=note: print w/replies, xml ) Need Help??


in reply to Generating basic time intervals between two times

Converting the hh24:mm format into seconds since midnight allows for greater simplification and modularisationg of the code.
use strict; use Data::Dumper; ################################################# #converts a string hh24:mm into seconds equivalent since midnight sub convert_to_seconds { my $time = shift; my ($hours, $minutes) = split ':', $time; return $hours * 3600 + $minutes * 60; } ################################################# #converts a seconds since midnight into hh24:mm format sub convert_to_hh24mm { my $time = shift; my $hours = int ($time / 3600); my $minutes = ($time % 3600) / 60; return sprintf("%02d:%02d", $hours, $minutes); } ################################################# #takes a begin and end time (in seconds since midnight) #and an interval (in seconds as well) as arguments sub generate_intervals { my ($begin, $end, $interval) = @_; my @intervals; while ($end > $begin) { push @intervals, $begin; $begin += $interval; } return @intervals; } ################################################# # M A I N # my $begintime = '18:20'; my $endtime = '22:30'; my $interval = 15; my @intervals = generate_intervals( convert_to_seconds($begintime), co +nvert_to_seconds($endtime), $interval * 60); foreach (@intervals){ print Dumper(convert_to_hh24mm($_) ); }
This outputs :

E:\>perl -w test.pl
$VAR1 = '18:20';
$VAR1 = '18:35';
$VAR1 = '18:50';
$VAR1 = '19:05';
$VAR1 = '19:20';
$VAR1 = '19:35';
$VAR1 = '19:50';
$VAR1 = '20:05';
$VAR1 = '20:20';
$VAR1 = '20:35';
$VAR1 = '20:50';
$VAR1 = '21:05';
$VAR1 = '21:20';
$VAR1 = '21:35';
$VAR1 = '21:50';
$VAR1 = '22:05';
$VAR1 = '22:20';

Jorg

"Do or do not, there is no try" -- Yoda

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://81819]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-24 01:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found