Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

timerender: Extract get_utc_offset_string helper.

Anders Kaseorg1e5bc2f2fd69
diff --git a/web/src/timerender.ts b/web/src/timerender.ts
index 752b962a694..0f854729509 100644
--- a/web/src/timerender.ts
+++ b/web/src/timerender.ts
@@ -158,6 +158,15 @@ export function get_localized_date_or_time_for_format(
return formatter_map.get(format_key)!.format(date);
}
+// Returns the UTC offset of the given time zone at the given time,
+// formatted like "UTC+05:30".
+export function get_utc_offset_string(time_zone: string, time: Date): string {
+ const offset_minutes = tzOffset(time_zone, time);
+ return `UTC${offset_minutes < 0 ? "-" : "+"}${String(
+ Math.floor(Math.abs(offset_minutes) / 60),
+ ).padStart(2, "0")}:${String(Math.abs(offset_minutes) % 60).padStart(2, "0")}`;
+}
+
// Exported for tests only.
export function get_tz_with_UTC_offset(time: Date): string {
let timezone = new Intl.DateTimeFormat(user_settings.default_language, {
@@ -176,10 +185,7 @@ export function get_tz_with_UTC_offset(time: Date): string {
// show that along with (UTC+x:y)
timezone = /GMT[+-][\d:]*/.test(timezone ?? "") ? "" : timezone;
- const offset_minutes = tzOffset(display_time_zone, time);
- const tz_UTC_offset = `(UTC${offset_minutes < 0 ? "-" : "+"}${String(
- Math.floor(Math.abs(offset_minutes) / 60),
- ).padStart(2, "0")}:${String(Math.abs(offset_minutes) % 60).padStart(2, "0")})`;
+ const tz_UTC_offset = `(${get_utc_offset_string(display_time_zone, time)})`;
if (timezone) {
return timezone + " " + tz_UTC_offset;
diff --git a/web/tests/timerender.test.cjs b/web/tests/timerender.test.cjs
index 84fa5bc1e7e..03c38c8823b 100644
--- a/web/tests/timerender.test.cjs
+++ b/web/tests/timerender.test.cjs
@@ -193,6 +193,19 @@ run_test("get_tz_with_UTC_offset", () => {
timerender.set_display_time_zone("UTC");
});
+run_test("get_utc_offset_string", () => {
+ // Offsets depend on the date: standard time vs. daylight saving time.
+ assert.equal(timerender.get_utc_offset_string("America/New_York", date_2025), "UTC-05:00");
+ assert.equal(timerender.get_utc_offset_string("America/New_York", date_2019), "UTC-04:00");
+
+ // Fractional-hour offsets, positive and negative.
+ assert.equal(timerender.get_utc_offset_string("Asia/Kolkata", date_2025), "UTC+05:30");
+ assert.equal(timerender.get_utc_offset_string("America/St_Johns", date_2025), "UTC-03:30");
+ assert.equal(timerender.get_utc_offset_string("America/St_Johns", date_2019), "UTC-02:30");
+
+ assert.equal(timerender.get_utc_offset_string("UTC", date_2025), "UTC+00:00");
+});
+
run_test("render_now_returns_today", () => {
clock.setSystemTime(date_2019.getTime());