SPUG: localtime() returning hour in wrong range?

Tim Maher tim at consultix-inc.com
Sun Apr 8 12:52:43 PDT 2007


On Sun, Apr 08, 2007 at 10:50:45AM -0700, Tim Maher wrote:
> SPUGsters,
> 
> The Camel coyly avoids specifying the ranges for most of localtime's
> various return values, but gives the hint that they follow (time.h's)
> "struct tm", which has the hour coded as 0-23.
> 
> So why does the following program display a localtime-derived hour
> value that /matches/ the one returned by the Linux date command,
> rather than a value that's less by one? E.g., if date says it's 11
> AM, shouldn't $hour be 10, not 11? Am I overlooking something?
> 
> #! /usr/bin/perl -wl
> # Tim Maher, tim at TeachMePerl.com
> 
> system 'date';  # show for comparison
> (undef, $minutes, $hour)=localtime;
> print "\$hour/\$minutes returned by localtime(): $hour/$minutes";

Reading the Camel more closely, it says "You can remember which ones
[localtime return values] are zero-based because those are the ones
you're always using as subscripts ...". Since one would very rarely
use an hour as a subscript (as one would a day number to retrieve the
corresponding day name from a list, e.g.), that explains why hours are
counted from 1.

Unfortunately, that reality conflicts with the suggestion of a 0-based
numeric range provided by the Camel's statement that "All list elements
are numeric and come straight out of a struct tm", as well as the explicit
statements in various books (e.g., Jon Orwant's "Perl 5 Interactive Course")
which reinforce the erroneous belief that localtime hours are 0..23.

As the great logician Chico Marx once (sorta) said,

        "Who you gonna believe--what it says in this book,
         or your own program?"

-Tim
*-------------------------------------------------------------------*
|  Tim Maher, PhD  (206) 781-UNIX   http://www.consultix-inc.com    |
|  tim at ( Consultix-Inc, TeachMePerl, or TeachMeUnix ) dot Com    |
| CLASSES: 4/23: Perl+CGI; 5/7: Basic UNIX/Linux; 5/11: Perl Hashes |
*-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-*
| >> My "Minimal Perl" is an Amazon Best Seller; 5 star rating! <<  |
| # Download chapters, read reviews, and order at MinimalPerl.com # |
*-------------------------------------------------------------------*


More information about the spug-list mailing list