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

I am taking a time() session variable, which can be somewhere in the past, and I am trying to figure out how many, minutes and seconds are seperating the two...

e.g:
my $_session_time = $session{time_then}; my $_current_time = time(); my $_time_now = ($_current_time-$_session_time)/60;
How can I format $_time_now in minutes and seconds. For instance, 30:05 = 30 minutes and 5 seconds.

Does perl have something built in that can do that?

Thanks,
Richard

Replies are listed 'Best First'.
Re: Time Formatting....
by Zaxo (Archbishop) on Aug 04, 2003 at 06:01 UTC

    Your $_time_now is a float, in minutes. You could multiply its fractional part by 60 to get the seconds back, but here is another way which works on elapsed seconds, ($_current_time - $_session_time),

    sub fmin_sec { my $sec = shift; sprintf '%01d:%02d', $sec / 60, $sec % 60; }

    After Compline,
    Zaxo

Re: Time Formatting....
by mpd (Monk) on Aug 04, 2003 at 06:04 UTC
    One way to do it yourself would be:
    # assuming $_session_time is in seconds. my $_session_time = $session{time_then}; my $_current_time = time(); my $_time_now = ($_current_time-$_session_time); my $minutes = int($_time_now / 60); my $seconds = $_time_now % 60;

    Though this will likely fail during time changes if they are observed where this code is being run.

    Alternatives include DateTime, Date::Calc, and Date::Manip.

    Code lightly tested. "It works for me."

      In addition to those modules I would recommend taking a look at Date::Format. It may not have as many features as the other ones, but for simple formatting like you are wanting to do it is very easy and straightforward to use. Also included in that distribution is Date::Parse which can be used to parse simple dates which I find useful for when you are fairly certain what format a date will be entered in but want to be a little flexible with the user.
Re: Time Formatting....
by bobn (Chaplain) on Aug 04, 2003 at 05:51 UTC

    perldoc -f localtime

    After getting difference in time() values, use the list output of localtime to make up the days, hours, minutes,seconds, etc. The year will be in 1970 or some such, but given your problem description, I think you just ignore that. Not tested, but ought to work.

    --Bob Niederman, http://bob-n.com

      For that to be convenient, you need to convert to UTC by adding your std TZ offset times 3600 sec/hour.

      After Compline,
      Zaxo