Skip to content

Commit

Permalink
LibTimeZone: Add methods to canonicalize a time zone name
Browse files Browse the repository at this point in the history
  • Loading branch information
trflynn89 authored and linusg committed Jan 10, 2022
1 parent 1c2c98a commit e9c42d0
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Tests/LibTimeZone/TestTimeZone.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,19 @@ TEST_CASE(time_zone_to_string_link)
EXPECT_EQ(TimeZone::time_zone_to_string(TimeZone::TimeZone::Etc_Universal), "Etc/UTC"sv);
}

TEST_CASE(canonicalize_time_zone)
{
EXPECT_EQ(TimeZone::canonicalize_time_zone("America/New_York"sv), "America/New_York"sv);
EXPECT_EQ(TimeZone::canonicalize_time_zone("AmErIcA/NeW_YoRk"sv), "America/New_York"sv);

EXPECT_EQ(TimeZone::canonicalize_time_zone("UTC"sv), "UTC"sv);
EXPECT_EQ(TimeZone::canonicalize_time_zone("GMT"sv), "UTC"sv);
EXPECT_EQ(TimeZone::canonicalize_time_zone("GMT+0"sv), "UTC"sv);
EXPECT_EQ(TimeZone::canonicalize_time_zone("GMT-0"sv), "UTC"sv);
EXPECT_EQ(TimeZone::canonicalize_time_zone("Etc/UTC"sv), "UTC"sv);
EXPECT_EQ(TimeZone::canonicalize_time_zone("Etc/GMT"sv), "UTC"sv);

EXPECT(!TimeZone::canonicalize_time_zone("I don't exist"sv).has_value());
}

#endif
13 changes: 13 additions & 0 deletions Userland/Libraries/LibTimeZone/TimeZone.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,17 @@ namespace TimeZone {
Optional<TimeZone> __attribute__((weak)) time_zone_from_string(StringView) { return {}; }
StringView __attribute__((weak)) time_zone_to_string(TimeZone) { return {}; }

Optional<StringView> canonicalize_time_zone(StringView time_zone)
{
auto maybe_time_zone = time_zone_from_string(time_zone);
if (!maybe_time_zone.has_value())
return {};

auto canonical_time_zone = time_zone_to_string(*maybe_time_zone);
if (canonical_time_zone.is_one_of("Etc/UTC"sv, "Etc/GMT"sv))
return "UTC"sv;

return canonical_time_zone;
}

}
1 change: 1 addition & 0 deletions Userland/Libraries/LibTimeZone/TimeZone.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ namespace TimeZone {

Optional<TimeZone> time_zone_from_string(StringView time_zone);
StringView time_zone_to_string(TimeZone time_zone);
Optional<StringView> canonicalize_time_zone(StringView time_zone);

}

0 comments on commit e9c42d0

Please sign in to comment.