How can I get and use custom TZ settings from my .bashrc in a Perl CGI script?

Each of my users has (possibly) different TZ defined in their .bashrc. I have a Perl script that displays the date / time and wants it to be displayed with the time zone of its profile.

Does anyone know a better way to do this?

+4
source share
3 answers

The 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 GMT Daylight Time and BST on two different platforms.

Edit The following is an experiment showing that (at least for me)% Z takes into account 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)' 

Outputs

  16:45 UTC 09:45 PDT 
+3
source

You can use the wonderful DateTime module 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:

Current time: 2010-04-19 20:09:03 CEST

How to extract timezone data from a user file: A quick solution is to save this user's TZ configuration in a separate file (which may be the source of .bashrc), and you can manually analyze it in CGI (however this gets into another topic: what is the best way to store configurations for each user for 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. 
+3
source

What is a profile in this context?

0
source

Source: https://habr.com/ru/post/1307355/


All Articles