Neil Ang

Developer

A stunning likeness of Neil Ang
Hello world

Converting seconds into a readable format in Perl

Posted on

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.