develooper Front page | perl.perl5.porters | Postings from November 1999

Re: [ID 19991103.010] bug in Localtime

Russ Allbery
November 3, 1999 23:50
Re: [ID 19991103.010] bug in Localtime
Message ID:
Rob van den Broeck <> writes:

> I found a problem using the function localtime. Executing the below script
> will give me a wrong value for $mon (10 i.s.o. 11):

> ($sec,$min,$hour,$day,$mon,$year,$wday,$yday,$isdst) = localtime(time) ; 
> printf "$year/$mon/$day\n"; 
> printf "$hour:$min:$sec\n"; 
> printf "$]\n"; 

> output: 

> 99/10/3
> 12:12:2 
> 5.00503 

=item localtime EXPR

Converts a time as returned by the time function to a 9-element array
with the time analyzed for the local time zone.  Typically used as

    #  0    1    2     3     4    5     6     7     8
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =

All array elements are numeric, and come straight out of a struct tm.  In
particular this means that C<$mon> has the range C<0..11> and C<$wday> has
the range C<0..6> with sunday as day C<0>.  Also, C<$year> is the number
of years since 1900, that is, C<$year> is C<123> in year 2023, and I<not>
simply the last two digits of the year.

If EXPR is omitted, uses the current time (C<localtime(time)>).

In scalar context, returns the ctime(3) value:

    $now_string = localtime;  # e.g., "Thu Oct 13 04:54:34 1994"

This scalar value is B<not> locale dependent, see L<perllocale>, but
instead a Perl builtin.  Also see the C<Time::Local> module, and the
strftime(3) and mktime(3) function available via the POSIX module.  To get
somewhat similar but locale dependent date strings, set up your locale
environment variables appropriately (please see L<perllocale>) and try for

    use POSIX qw(strftime);
	$now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;

Note that the C<%a> and C<%b>, the short forms of the day of the week and
the month of the year, may not necessarily be three characters wide.

Russ Allbery (         <URL:> Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About