On 5/2/11 Mon  May 2, 2011  9:46 AM, "Matt" <lm7...@gmail.com> scribbled:

> 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";

That program fragment does not run on my system:

"Can't locate object method "year" via package "Mon May  2 17:16:09 2011"
(perhaps you forgot to load "Mon May  2 17:16:09 2011"?) at matt1.pl line
8."

The standard gmtime returns a date/time string in scalar context. You are
apparently using some other gmtime method that returns a blessed object.

It is always better to post complete programs so that people trying to help
you know don't have to figure out what you are doing.


> 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?

Rounding of times is best done using a numerical representation of the time,
as provided by the time() builtin function. Round that value as needed and
then display it using component values. Here is a sample program:

#!/usr/local/bin/perl
use strict;
use warnings;

my $five_min = 5 * 60;

my $t = time;
my $t5min = int($five_min * (int( ($t/$five_min) + 0.5 )));

print "t=$t, t5min=$t5min\n";
my @gmt = gmtime($t);
my @gmt5min = gmtime($t5min);

print "gmt=@gmt\ngmt5min=@gmt5min\n";

my $time_stamp = sprintf "%04d-%02d-%02d-%02d:%02d:%02d",
 ($gmt[5] + 1900), ($gmt[4] + 1), $gmt[3], $gmt[2], $gmt[1], $gmt[0];

my $time_stamp5min = sprintf "%04d-%02d-%02d-%02d:%02d:%02d",
 ($gmt5min[5] + 1900), ($gmt5min[4] + 1), $gmt5min[3],
 $gmt5min[2], $gmt5min[1], $gmt5min[0];

print "      time stamp = $time_stamp\n";
print "time stamp 5 min = $time_stamp5min\n";


As Uri recommends, there are several good date/time modules to help you do
the display.



-- 
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