1. Technology

Localtime - How to Tell the Current Time in Perl

Making the Perl Localtime Readable

By

Next: How to tell the current GM Time in Perl

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.

 #!/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; 
When you run the program, you should see a much more readable date and time like this:
 9:14:42, Wed Dec 28, 2005 
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.
 @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
 @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun); 
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[$month] $weekDays[$dayOfWeek]
 
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.
 ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
 
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.
 $year = 1900 + $yearOffset;
 
Next: How to tell the current GM Time in Perl
  1. About.com
  2. Technology
  3. Perl
  4. Perl Tutorials
  5. Localtime - How to Tell the Current Time in Perl

©2014 About.com. All rights reserved.