Human Friendly Time
December 13, 1999
Perl possesses two built-in functions which happily translate
the epoch time format into a more human friendly
format. Both
gmtime and
localtime
can be used
to print out the current time and/or extract the various
elements from an epoch time, such as month, hours, minutes,
and so on. Whereas
gmtime
returns all of these
values relative to Greenwich Mean Time, localtime
adjusts its values to the local time on your own machine.
This assumes, of course, that your operating system is
properly configured to your time zone.
We'll look at the use of localtime, but remember that
gmtime works exactly the same way and supports
exactly the same syntax, but that it simply returns GMT time
which is not corrected for your time zone.
The simplest way to use localtime is in "scalar
context". For instance:
print scalar localtime(time);
Yields:
Wed Dec 8 10:16:31 1999
Remember that time represents the up-to-the-second
epoch time; you can use localtime to print
a human friendly version of any epoch time ... for example:
print scalar localtime(420221050);
Yields:
Tue Apr 26 12:04:10 1983
Right away, you can begin to see some potential usefulness
in the way Perl views time in epoch seconds. Consider
time calculations. Imagine that you know the current time,
and you wish to calculate the date 24 hours ahead. Not
as simple as it sounds if you think of the human calendar
because some dates will rollover to a new month or even
a new year when you add 24 hours. We needn't worry about
these complications. Look at this way, instead: one day
consists of 24 hours. An hour consists of 60 minutes, and
a minute consists of 60 seconds. Therefore, a full day
consists of 60*60*24, or 86,400 seconds.
$now=time;
$tomorrow=$now+86400;
print scalar localtime($tomorrow);
It is therefore quite simple to add or subtract periods of
time, when you do all your calculations in epoch
seconds. You then let Perl's localtime function worry
about converting the epoch time into the proper year,
day, month, and time. The handy table below summarizes a
number of time periods and their epoch second equivalents.
Periods of time represented in seconds since the January 1,
1970 epoch.
| 1 hour |
3600 |
| 1 day |
86400 |
| 1 week |
604800 |
| 2 weeks |
1209600 |
| 3 weeks |
1814400 |
| 1 month |
2419200 |
| 6 months |
14515200 |
| 1 year |
29030400 |
| 1 decade |
290304000 |
The Perl You Need to Know Part 9:The Millennium Episode -- Time and Date Manipulation
The Perl You Need to Know
Chopped Time
|