Unix time to Human Readable time using Perl localtime
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
- Seconds
- Minutes
- Hours
- Day of the month
- Month
- Year
- Day of the week
- Day of the year
- 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.
Comments:
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=9c747e39-0f5e-4a1e-a0a9-a769d0b004f2)