On 02/05/2011 17:46, Matt wrote:
Have a date:
2011-05-02-16:40:51
Using this to get it:
$tm = gmtime;
$time_stamp = sprintf "%04d-%02d-%02d-%02d:%02d:%02d",
$tm->year + 1900, $tm->mon + 1, $tm->mday, $tm->hour, $tm->min, $tm->sec;
print "$time_stamp\n";
I need to round it to nearest 5 minute point.
2011-05-02-16:40:51
needs rounded like so.
2011-05-02-16:00:00
2011-05-02-16:45:00
2011-05-02-16:50:00
2011-05-02-16:55:00
My thought is a bunch of if statements but that seems ugly. Is there
a better/easier way?
Hey Matt
It is a lot easier to round to the nearest five minutes while the time
is held in epoch seconds. Instead of letting gmtime() do an implicit
call to time(), you can do an explicit one, round the result, and pass
it to gmtime() for reformatting.
The code below shows my point.
HTH,
Rob
use strict;
use warnings;
use constant FIVE_MINS => 5 * 60;
my $t = time;
my $secs = $t % FIVE_MINS;
$t -= $secs;
$t += FIVE_MINS if $secs >= FIVE_MINS / 2;
my @time = reverse((gmtime($t))[0..5]); # Grab [ Y M D h m s ]
$time[0] += 1900; # Correct the year
$time[1] += 1; # And the month
printf "%04d-%02d-%02d-%02d:%02d:%02d", @time;
**OUTPUT**
2011-05-03-11:05:00
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/