You are here:About>Computing & Technology>Perl> Perl Tutorials> localtime - How to tell the current time in Perl
About.comPerl
Newsletters & RSSEmail to a friendSubmit to Digg

localtime - How to tell the current time in Perl

From Kirk Brown,
Your Guide to Perl.
FREE Newsletter. Sign Up Now!

How to tell the current GM Time in Perl

Next: How to tell the current GM Time in Perl

Let's say that you want to avoid all possible timezone confusions and take control of the offset yourself. Getting the current time in localtime will always return a value that is based on the machine's timezone settings - a server in the US will return one time, while a server in Australia will return one nearly a full day different due to the timezone differences.

Perl has a second handy time telling function that works in exactly the same way as localtime, but instead of returning the time fixed for your machines timezone, it returns Coordinated Universal Time (abbreviated as UTC, also called Greenwich Mean Time or GMT). Simply enough the function is called gmtime

#!/usr/local/bin/perl
@timeData = gmtime(time);
print join(' ', @timeData);
Other than the fact the time returned will be the same on every machine (assuming their clocks are set correctly) and in GMT, there is no difference between the gmtime and localtime functions. All the data and conversions are done in the same way.
#!/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) = gmtime();
$year = 1900 + $yearOffset;
$theGMTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";
print $theGMTime;
  1. localtime will return the current local time on the machine that runs the script.
  2. gmtime will return the universal Greenwich Mean Time, or GMT (or UTC).
  3. The return values may not be quite what you expect, so make sure you convert them as necessary.
Previous: Making the perl localtime readable
 All Topics | Email Article | | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.