Unix time to Human Readable time using Perl localtime

Posted by Joys of Programming on in Perl

Perl has a function time to get the current time. But the function returns the Epoch time, which is number of seconds that have passed since January 1 1970

So a simple program like


my $time = time();
print $time;

will give an output like


1258982241115

which is unreadable to the users.

To convert this time to human readable format, you can make use of the function localtime.

localtime returns a 9 element list which consists of the following elements in the order

  1. Seconds
  2. Minutes
  3. Hours
  4. Day of the month
  5. Month
  6. Year
  7. Day of the week
  8. Day of the year
  9. Daylight Saving Time

Now you can make use of this information to convert the epoch time to a human readable format. All the above fields are readable.

Daylight saving time is the practice of advancing clocks so that afternoons have more daylight and mornings have less.


my $time = time();

my ($sec, $min, $hours, $mday, $month, $year, $wday, $yday, $isdst) = localtime($time);

my @day = qw (Sunday Monday Tuesday Wednesday Thursday Friday Saturday);

my @month_name = qw (January February March April May June July August September October November December);

print $day[$wday], " ",$month_name[$month], " ",$mday," ", $hours,":",$min,":",$sec, " ",1900+$year,"\n"

which generates an output in the following manner


Monday November 23 19:24:45 2009

You would have noticed certain interesting aspects of the program.

$month and $wday are numeric values corresponding to month and week day respectively. Week starts on Sunday.

Also you would have noticed that we are adding 1900 to $year. This is because localtime returns the number of years passed since 1900.

Reblog this post [with Zemanta]


Tags: ,

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.