TimeZone.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (c) 2022, Tim Flynn <trflynn89@pm.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibTimeZone/TimeZone.h>
  7. #include <time.h>
  8. namespace TimeZone {
  9. // NOTE: Without ENABLE_TIME_ZONE_DATA LibTimeZone operates in a UTC-only mode and only recognizes
  10. // the 'UTC' time zone, which is slightly more useful than a bunch of dummy functions that
  11. // can't do anything. When we build with time zone data, these weakly linked functions are
  12. // replaced with their proper counterparts.
  13. #if !ENABLE_TIME_ZONE_DATA
  14. enum class TimeZone : u16 {
  15. UTC,
  16. };
  17. #endif
  18. StringView current_time_zone()
  19. {
  20. static bool initialized_time_zone = false;
  21. if (!initialized_time_zone) {
  22. initialized_time_zone = true;
  23. tzset();
  24. }
  25. return canonicalize_time_zone(tzname[0]).value_or("UTC"sv);
  26. }
  27. Optional<TimeZone> __attribute__((weak)) time_zone_from_string([[maybe_unused]] StringView time_zone)
  28. {
  29. #if !ENABLE_TIME_ZONE_DATA
  30. if (time_zone.equals_ignoring_case("UTC"sv))
  31. return TimeZone::UTC;
  32. #endif
  33. return {};
  34. }
  35. StringView __attribute__((weak)) time_zone_to_string([[maybe_unused]] TimeZone time_zone)
  36. {
  37. #if !ENABLE_TIME_ZONE_DATA
  38. VERIFY(time_zone == TimeZone::UTC);
  39. return "UTC"sv;
  40. #else
  41. return {};
  42. #endif
  43. }
  44. Optional<StringView> canonicalize_time_zone(StringView time_zone)
  45. {
  46. auto maybe_time_zone = time_zone_from_string(time_zone);
  47. if (!maybe_time_zone.has_value())
  48. return {};
  49. auto canonical_time_zone = time_zone_to_string(*maybe_time_zone);
  50. if (canonical_time_zone.is_one_of("Etc/UTC"sv, "Etc/GMT"sv))
  51. return "UTC"sv;
  52. return canonical_time_zone;
  53. }
  54. Optional<i64> __attribute__((weak)) get_time_zone_offset([[maybe_unused]] TimeZone time_zone, AK::Time)
  55. {
  56. #if !ENABLE_TIME_ZONE_DATA
  57. VERIFY(time_zone == TimeZone::UTC);
  58. return 0;
  59. #else
  60. return {};
  61. #endif
  62. }
  63. Optional<i64> get_time_zone_offset(StringView time_zone, AK::Time time)
  64. {
  65. if (auto maybe_time_zone = time_zone_from_string(time_zone); maybe_time_zone.has_value())
  66. return get_time_zone_offset(*maybe_time_zone, time);
  67. return {};
  68. }
  69. }