This is the personal blog of Neil Ang. Simple and interesting technology articles written by a developer for developers. Feel free to comment on posts or link to this site. Constructive feedback is always welcomed.

Converting seconds into a readable format in Perl

Posted: 18 June 2008

Here is a short and easy Perl function to convert the difference between two time stamps, into something that is more human readable. There are Perl modules that can do this as well, however I thought I would share what I wrote incase someone finds it useful.

#!/usr/bin/env perl -w

sub convert_time {
  my $time = shift;
  my $days = int($time / 86400);
   $time -= ($days * 86400);
  my $hours = int($time / 3600);
   $time -= ($hours * 3600);
  my $minutes = int($time / 60);
  my $seconds = $time % 60;

  $days = $days < 1 ? '' : $days .'d ';
  $hours = $hours < 1 ? '' : $hours .'h ';
  $minutes = $minutes < 1 ? '' : $minutes . 'm ';
  $time = $days . $hours . $minutes . $seconds . 's';
  return $time;
}

When using this function, these are the outputs you should see:

print convert_time(1); # result: 1s
print convert_time(61); # result: 1m 1s
print convert_time(3661); # result: 1h 1m 1s
print convert_time(90061); # result: 1d 1h 1m 1s

This code can easily be modified to output other formats as well. Let me know if you come up with something different.

Your comments

No comments have been made. Why not be the first?

Post a comment

Comment Guidelines

  • Have no more than 2 links, otherwise your comment will be flagged as spam.
  • Links are automagically generated.
  • <em>text</em> to make text italic.
  • <strong>text</strong> to make text bold.

JavaScript needs to be enabled to comment.