I had assumed it would be as simple as $ENV{TZ}
, but the TZ
environment variable is not set, and yet the date
command still knows I am in EDT, so there must be some other way of determining timezone (other than saying chomp(my $tz = qx/date +%Z/);
).
localtime() function in Perl returns the current date and time of the system, if called without passing any argument.
Use POSIX::tzset.
The Perl POSIX strftime() function is used to format date and time with the specifiers preceded with (%) sign. There are two types of specifiers, one is for local time and other is for gmt time zone.
You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz. all_timezones print(zones) # Output: all timezones of the world.
If you want something more portable than POSIX
(but probably much slower) you can use DateTime::TimeZone for this:
use DateTime::TimeZone;
print DateTime::TimeZone->new( name => 'local' )->name();
use POSIX;
localtime();
my ($std, $dst) = POSIX::tzname();
tzname()
gives you access to the POSIX global tzname
- but you need to have called localtime()
for it to be set in the first place.
If you just need something like +05:30
(UTC+5.5/India time), you may use the following code.
my @lt = localtime();
my @gt = gmtime();
my $hour_diff = $lt[2] - $gt[2];
my $min_diff = $lt[1] - $gt[1];
my $total_diff = $hour_diff * 60 + $min_diff;
my $hour = int($total_diff / 60);
my $min = abs($total_diff - $hour * 60);
print sprintf("%+03d:%02d", $hour, $min);
This answer is inspired by Pavel's answer above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With