capriguy84 has asked for the wisdom of the Perl Monks concerning the following question:

Is there a perl module or way to round-off time to nearest second?
15:59:57.203 = 15:59:57
(It doesn't matter if the millisecond greater than 500 has to be rounded to next second).

Replies are listed 'Best First'.
Re: Round off Time to nearest second
by JavaFan (Canon) on Sep 16, 2011 at 18:02 UTC
    If you don't care where you round to 0 or to nearest, just truncate:
    $time =~ s/\..*//;
    If you know the time has formate "HH:MM:SS.FRACTION" (that is, you always have 2 digits for hours, minutes, seconds), you can also do:
    substr $time, 8, -1, ""; # Or $time = substr $time, 0, 8;
Re: Round off Time to nearest second
by ikegami (Patriarch) on Sep 16, 2011 at 18:54 UTC
Re: Round off Time to nearest second
by Anonymous Monk on Sep 16, 2011 at 16:50 UTC
    Just add half a second to the time, then truncate to the second.
    use DateTime::Format::Strptime qw(); DateTime::Format::Strptime ->new(pattern => '%T.%N') ->parse_datetime('15:59:57.203') ->add(nanoseconds => 0.5 * 1000 * 1000 * 1000) ->truncate(to => 'second') ->strftime('%T'); # returns '15:59:57' DateTime::Format::Strptime ->new(pattern => '%T.%N') ->parse_datetime('15:59:57.703') ->add(nanoseconds => 0.5 * 1000 * 1000 * 1000) ->truncate(to => 'second') ->strftime('%T'); # returns 15:59:58