A few of the elements in the array that localtime returns are a bit awkward for humans to read. Who would think of the current year in terms of the number of years past 1900? Lets take a look at an example that makes our date and time clearer.
When you run the program, you should see a much more readable date and time like this:
#!/usr/local/bin/perl @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun); ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime(); $year = 1900 + $yearOffset; $theTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year"; print $theTime;
So what did we do to create this more readable version? First we prepare two arrays with the names of the months and days of the week.
9:14:42, Wed Dec 28, 2005
Since the localtime function returns these elements in values ranging from 0-11 and 0-6 respectively, they are perfect candidates for an array. The value returned by localtime can be used as a numeric address to access the correct element in the array.
@months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
The next step is to get all the values from the localtime function. In this example, we're using a little Perl shortcut to automatically place each element in the localtime array into its own variable. We've chosen names so that it's easy to remember which element is which.
We also need to adjust the value of the year. Remember that localtime returns the number of years since 1900, so in order to find the current year, we'll need to add 1900 to the value we're given.
($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
Next: How to tell the current GM Time in Perl
$year = 1900 + $yearOffset;