On May 2, 9:46 am, lm7...@gmail.com (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?

The Modern Perl suggestion when dealing with dates and times is to use DateTime. It is well tested and should handle edge cases you may not have considered. After all, what do you do when you want to round up from 2011-12-24 23:58:00?

You can use Math::Round to do the rounding for you.

Cheers,
Pete

use DateTime;
use DateTime::Duration;
use Math::Round 'nearest';

# create a DateTime object for now - see the docs:
# http://search.cpan.org/perldoc?DateTime
my $dt = DateTime->now;

# you should set time zone as you may be in DST
$dt->set_time_zone( 'Europe/London' );

# create a DateTime::Duration of nearest 5 minutes
my $duration = DateTime::Duration->new(
    minutes => nearest(5, $dt->minute)
);

# this truncates the time to the hour - you can truncate to any unit of
# time
$dt->truncate(to => 'hour');

# you can add durations to DateTime objects using addition and
# subtraction operators
$dt += $duration;

# DateTime objects can be printed in scalar context
print $dt, "\n";


NET-A-PORTER.COM Irresistible fashion at your fingertips

______________________________________________________________________

CONFIDENTIALITY NOTICE
The information in this email is confidential and is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, you must not read, use or disseminate the information. Any views expressed in this message are those of the individual sender, except where the sender specifically states them to be the views of Net a Porter Ltd.
Net A Porter Ltd is a company registered in England & Wales Number: 3820604 
Registered Office: 1 The Village Offices, Westfield, Ariel Way, London, W12 7GF
_____________________________________________________________________

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to