How can I get and use a user's TZ setting from their .bashrc in a Perl CGI script?
Each of my users has a (possibly) different TZ defined in their .bashrc. I have a Perl script that displays date/time and want it to h开发者_如何学Cave it display with their profile time zone.
Does anyone know the best way to do this?
A simple answer is to use:
use POSIX;
....
print strftime("%H:%M %Z", localtime);
But the zone returned by %Z varies from system to system. I have got GMT Daylight Time
and BST
on two different platforms.
Edit The following is an experiment showing that (at least for me) %Z takes account of TZ
export TZ=''
perl -MPOSIX -e 'print strftime("%H:%M %Z\n", localtime)'
export TZ=America/Los_Angeles
perl -MPOSIX -e 'print strftime("%H:%M %Z\n", localtime)'
Produces output
16:45 UTC
09:45 PDT
You can use the wonderful module DateTime for this:
use strict; use warnings;
use DateTime;
# extract timezone name from file in env variable
(my $tz = $ENV{TZ}) =~ s#^/usr/share/zoneinfo/##;
my $now = DateTime->now(time_zone => $tz);
print "The current time is: " . $now->strftime('%F %T %Z') . "\n";
When I run this with TZ="/usr/share/zoneinfo/Europe/Paris", I see:
The current time is: 2010-04-19 20:09:03 CEST
As for extracting the timezone data from the user's file: a quick solution is to store that user's TZ configuration in a separate file (which .bashrc could source), and you can parse it manually in the CGI (however this gets into a different topic: How can I best store per-user configurations for a CGI?)
# /home/<user>/.tz should have the content: export TZ="/usr/share/zoneinfo/timezonename"
open(my $tz_fh, "/home/${user}/.tz");
chomp(my $tz_data = <$tz_fh>);
close $tz_fh;
(my $tz_path) = $tz_data =~ m/^export TZ\s*=\s*"(.+)"$/;
# now $tz_path contains what $ENV{TZ} would contain in the earlier code snippet.
Whats a "profile" in this context?
精彩评论