Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

The DateTime documentation implies that it respects $ENV{TZ}. But I've set the TZ environment and DateTime still defaults to UTC, so I have to pass time_zone argument to the constructor each time (e.g. my $today = DateTime->today(time_zone=>$ENV{TZ})). How can I make DateTime use $ENV{TZ} by default?

Replies are listed 'Best First'.
Re: DateTime not observing $ENV{TZ} by default?
by Anonymous Monk on Jul 21, 2011 at 00:13 UTC

    The DateTime documentation implies that it respects $ENV{TZ}

    No it doesn't. The documentation says

    Determining the local time zone for a system can be slow. If $ENV{TZ} is not set, it may involve reading a number of files in /etc or elsewhere. If you know that the local time zone won't change while your code is running, and you need to make many objects for the local time zone, it is strongly recommended that you retrieve the local time zone once and cache it:
    our $App::LocalTZ = DateTime::TimeZone->new( name => 'local' ); ... # then everywhere else my $dt = DateTime->new( ..., time_zone => $App::LocalTZ );

    So its explicit, use time_zone => 'local'

      Well, I read this sentence:
      If $ENV{TZ} is not set, it may involve reading a number of files in /etc or elsewhere.
      to mean that DateTime checks $ENV{TZ}. Oh well.
Re: DateTime not observing $ENV{TZ} by default?
by pemungkah (Priest) on Jul 21, 2011 at 01:49 UTC
    Also, to dynamically swap timezones, use tzset from POSIX. (I did not know about this until last week, and it helped me solve a five-year-old bug. Doesn't work on Windows, though.)
    $ENV{TZ} = "CEST"; tzset;

      Thanks, DateTime ignores it though.

      So is explicit argument to constructor the only way to do it? Doesn't seem very Perlish to me :-)

        So is explicit argument to constructor the only way to do it?

        Yes, its the only way; you could create alternate constructor, or propose a patch for one

        Doesn't seem very Perlish to me :-)

        Why? time doesn't consult ENV{TZ} and neither does gmtime -- The module is called DateTime not, localtime :)