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 have it display with their profile time zone.
Does anyone know the best way to do this?
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 have 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 sysetm. I have got GMT Daylight Time
and BST
on two different platforms.
Edit The following is an experminet showing that (at least for me) %Z takes account ot 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.