1. Technology

Localtime - How to Tell the Current Time in Perl

Using Localtime to Find the Time in Your Perl Scripts


Next: Making the perl localtime readable

Perl has a handy built-in function for finding the current date and time in your scripts. Keep in mind, though, that when we talk about finding the time, we're talking about the time that is currently set on the machine that's running the script. For instance, if you're running your Perl script on your local machine, localtime will return the current time you have set, and presumably set to your current timezone.

When you run the same script on a web server though, you may find that localtime there is off from localtime on your desktop system. The server might be in a different time zone, or be set incorrectly. Each machine may have a totally different idea of what localtime is and it may take some adjusting, either within the script or on the server itself, to get it to match up to what you're expecting.

The localtime function returns a list full of data about the current time, some of which will need to be adjusted. Run the program below and you'll see each element in the list printed on the line and separated by spaces.

@timeData = localtime(time);
print join(' ', @timeData);
You should see something similar to this, although the number could be very different.
20 36 8 27 11 105 2 360 0
These elements of the current time are, in order:
  • Seconds past the minute
  • Minutes past the hour
  • Hours past midnight
  • Day of the month
  • Months past the start of the year
  • Number of years since 1900
  • Number of days since the start of the week (Sunday)
  • Number of days since the start of the year
  • Whether or not daylight savings is active
So if we return to the example and attempt to read it, you'll see that it's 8:36:20 AM on December the 27th, 2005, it's 2 days past Sunday (Tuesday), and it's 360 days since the start of the year. Daylight savings time is not currently active.

Next: Making the perl localtime readable

  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.