Skip to content
This repository has been archived by the owner on Oct 15, 2022. It is now read-only.

Timezones #4460

Closed
wants to merge 19 commits into from
Closed
70 changes: 37 additions & 33 deletions lib/DDG/Goodie/Timezonetime.pm
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use DDG::Goodie;
use strict;
use warnings;

use YAML::XS qw/LoadFile/;

use DateTime;
use DateTime::TimeZone;

Expand All @@ -15,51 +17,53 @@ triggers start => ("what time in", "what time is it in", "time in");
triggers startend => ("time", "now time", "time now");

# Mapping short timezone names to one used by DateTime:Timezone module
my $timezoneMapping = {
"IST" => "Asia/Kolkata",
"EST" => "EST",
"UTC" => "UTC",
"GMT" => "GMT",
"BST" => "Europe/London",
"PST" => "PST8PDT",
"CST" => "CST6CDT"
};

my $timezones = join('|', keys(%$timezoneMapping));
my $timezoneMapping = LoadFile(share('abbreviations.yaml'));

# Add a field (offset_seconds) with offsets converted to seconds.
for my $abbreviation (keys %{$timezoneMapping}) {
for my $timezone (@{$timezoneMapping->{$abbreviation}}) {
my $seconds = DateTime::TimeZone->offset_as_seconds($timezone->{offset});
$timezone->{offset_seconds} = $seconds;
}
}

handle remainder => sub {
my $query = $_;

my $daylightStatus = "";

my $timezone = uc($query);
my $mappedTimezone = $timezoneMapping->{$timezone} // 0;
return unless $mappedTimezone;

# Get time for desired timezone
my $tz = DateTime::TimeZone->new( name => $mappedTimezone );
my $dt = DateTime->now();
my $offset = $tz->offset_for_datetime($dt);
$dt->add(seconds => $offset);
my $time = $dt->hms(':');
my $mappedTimezones = $timezoneMapping->{$timezone} // 0;
return unless $mappedTimezones;

# Check if timezone is in daylight saving or not
if ($tz->is_dst_for_datetime( $dt )) {
$daylightStatus = "$timezone is in daylight saving";
}
else {
$daylightStatus = "$timezone is not in daylight saving";
# Get time for desired timezones
my $dt = DateTime->now(time_zone => 'UTC');
my @times = ();
for (@{$mappedTimezones}) {
my $dt_clone = $dt->clone;
$dt_clone->add(seconds => $_->{offset_seconds});
push @times, { name => $_->{name},
time => $dt_clone->hms(':'),
offset => $_->{offset},
day => $dt_clone->day,
dayName => $dt_clone->day_name,
monthName => $dt_clone->month_name,
year => $dt_clone->year };
}

return "$time $timezone $daylightStatus",
return "times in $timezone",
structured_answer => {

meta => {
sourceName => 'timeanddate',
sourceUrl => 'https://www.timeanddate.com/time/zones/'
},
data => {
title => "$time $timezone",
subtitle => "$daylightStatus",
title => "Timezone $timezone",
list => \@times
},
templates => {
group => 'text',
group => 'list',
options => {
list_content => 'DDH.timezonetime.content'
}
}
};
};
Expand Down
Loading