Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
time_zone_util: Replace with @date-fns/tz.
Anders Kaseorg70d41b8dba52
diff --git a/package.json b/package.jsonindex 38c502c99d4..3c3efaa5311 100644--- a/package.json+++ b/package.json@@ -6,6 +6,7 @@"@babel/core": "^7.5.5","@babel/preset-env": "^7.5.5","@babel/preset-typescript": "^7.15.0",+ "@date-fns/tz": "^1.4.1","@fontsource-variable/open-sans": "^5.0.9","@formatjs/intl": "^3.0.1","@gfx/zopfli": "^1.0.15",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d3c5679b444..3e3ca6b9d22 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -47,6 +47,9 @@ importers:'@babel/preset-typescript':specifier: ^7.15.0version: 7.28.5(@babel/[email protected])+ '@date-fns/tz':+ specifier: ^1.4.1+ version: 1.4.1'@fontsource-variable/open-sans':specifier: ^5.0.9version: 5.2.7@@ -1583,6 +1586,9 @@ packages:'@dabh/[email protected]':resolution: {integrity: sha512-R4MSXTVnuMzGD7bzHdW2ZhhdPC/igELENcq5IjEverBvq5hn1SXCWcsi6eSsdWP0/Ur+SItRRjAktmdoX/8R/Q==}+ '@date-fns/[email protected]':+ resolution: {integrity: sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==}+'@discoveryjs/[email protected]':resolution: {integrity: sha512-4B4OijXeVNOPZlYA2oEwWOTkzyltLao+xbotHQeqN++Rv27Y6s818+n2Qkp8q+Fxhn0t/5lA5X1Mxktud8eayQ==}engines: {node: '>=14.17.0'}@@ -11219,6 +11225,8 @@ snapshots:enabled: 2.0.0kuler: 2.0.0+ '@date-fns/[email protected]': {}+'@discoveryjs/[email protected]': {}'@dual-bundle/[email protected]': {}diff --git a/version.py b/version.pyindex b4f8df6be93..8b1f32225b6 100644--- a/version.py+++ b/version.py@@ -50,4 +50,4 @@ API_FEATURE_LEVEL = 436# historical commits sharing the same major version, in which case a# minor version bump suffices.-PROVISION_VERSION = (359, 0) # bumped 2025-11-20 to upgrade stripe python SDK+PROVISION_VERSION = (359, 1) # bumped 2025-11-22 to add @date-fns/tzdiff --git a/web/src/message_list_view.ts b/web/src/message_list_view.tsindex 74965c2b18c..16485d754d5 100644--- a/web/src/message_list_view.ts+++ b/web/src/message_list_view.ts@@ -1,4 +1,5 @@import autosize from "autosize";+import {isSameDay} from "date-fns";import $ from "jquery";import _ from "lodash";import assert from "minimalistic-assert";@@ -40,7 +41,6 @@ import * as stream_color from "./stream_color.ts";import * as stream_data from "./stream_data.ts";import * as sub_store from "./sub_store.ts";import * as submessage from "./submessage.ts";-import {is_same_day} from "./time_zone_util.ts";import * as timerender from "./timerender.ts";import type {TopicLink} from "./types.ts";import * as typing_data from "./typing_data.ts";@@ -138,11 +138,9 @@ function same_day(earlier_msg: Message | undefined, later_msg: Message | undefinif (earlier_msg === undefined || later_msg === undefined) {return false;}- return is_same_day(- earlier_msg.timestamp * 1000,- later_msg.timestamp * 1000,- timerender.display_time_zone,- );+ return isSameDay(earlier_msg.timestamp * 1000, later_msg.timestamp * 1000, {+ in: timerender.display_tz,+ });}function same_year(earlier_msg: Message | undefined, later_msg: Message | undefined): boolean {diff --git a/web/src/navbar_alerts.ts b/web/src/navbar_alerts.tsindex 7eb21e9076c..d178dc965b9 100644--- a/web/src/navbar_alerts.ts+++ b/web/src/navbar_alerts.ts@@ -1,4 +1,4 @@-import {addDays} from "date-fns";+import {addDays, differenceInCalendarDays} from "date-fns";import $ from "jquery";import assert from "minimalistic-assert";@@ -18,7 +18,6 @@ import {page_params} from "./page_params.ts";import * as people from "./people.ts";import * as popover_menus from "./popover_menus.ts";import {current_user, realm} from "./state_data.ts";-import * as time_zone_util from "./time_zone_util.ts";import * as timerender from "./timerender.ts";import * as ui_util from "./ui_util.ts";import * as unread from "./unread.ts";@@ -131,11 +130,7 @@ export function should_show_organization_profile_incomplete_banner(timestamp: nuconst today = new Date(Date.now());const time = new Date(timestamp * 1000);- const days_old = time_zone_util.difference_in_calendar_days(- today,- time,- timerender.display_time_zone,- );+ const days_old = differenceInCalendarDays(today, time, {in: timerender.display_tz});if (days_old >= 15) {return true;diff --git a/web/src/time_zone_util.ts b/web/src/time_zone_util.tsdeleted file mode 100644index 9b0def2f623..00000000000--- a/web/src/time_zone_util.ts+++ /dev/null@@ -1,65 +0,0 @@-const parsable_formats = new Map<string, Intl.DateTimeFormat>();--function get_parsable_format(time_zone: string): Intl.DateTimeFormat {- let format = parsable_formats.get(time_zone);- if (format === undefined) {- format = new Intl.DateTimeFormat("en-US", {- year: "numeric",- month: "numeric",- day: "numeric",- hour: "numeric",- minute: "numeric",- second: "numeric",- hourCycle: "h23",- timeZone: time_zone,- });- parsable_formats.set(time_zone, format);- }- return format;-}--/** Get the given time zone's offset in milliseconds at the given date. */-export function get_offset(date: number | Date, time_zone: string): number {- const parts = Object.fromEntries(- get_parsable_format(time_zone)- .formatToParts(date)- .map((part) => [part.type, part.value]),- );- return (- Date.UTC(- Number(parts.year),- Number(parts.month) - 1,- Number(parts.day),- Number(parts.hour),- Number(parts.minute),- Number(parts.second),- ) -- (Number(date) - (Number(date) % 1000))- );-}--/** Get the start of the day for the given date in the given time zone. */-export function start_of_day(date: number | Date, time_zone: string): Date {- const offset = get_offset(date, time_zone);- let t = Number(date) + offset;- t -= t % 86400000;- return new Date(t - get_offset(new Date(t - offset), time_zone));-}--/** Get the number of calendar days between the given dates (ignoring times) in- * the given time zone. */-export function difference_in_calendar_days(- left: number | Date,- right: number | Date,- time_zone: string,-): number {- return Math.round(- (start_of_day(left, time_zone).getTime() - start_of_day(right, time_zone).getTime()) /- 86400000,- );-}--/** Are the given dates in the same day in the given time zone? */-export function is_same_day(left: number | Date, right: number | Date, time_zone: string): boolean {- return start_of_day(left, time_zone).getTime() === start_of_day(right, time_zone).getTime();-}diff --git a/web/src/timerender.ts b/web/src/timerender.tsindex a76bc2dc83a..9578293a4e0 100644--- a/web/src/timerender.ts+++ b/web/src/timerender.ts@@ -1,17 +1,19 @@+import {tz, tzOffset} from "@date-fns/tz";import {+ differenceInCalendarDays,differenceInHours,differenceInMinutes,formatISO,isEqual,isValid,parseISO,+ startOfToday,} from "date-fns";import $ from "jquery";import render_markdown_time_tooltip from "../templates/markdown_time_tooltip.hbs";import {$t} from "./i18n.ts";-import {difference_in_calendar_days, get_offset, start_of_day} from "./time_zone_util.ts";import {parse_html} from "./ui_util.ts";import {user_settings} from "./user_settings.ts";import * as util from "./util.ts";@@ -19,6 +21,7 @@ import * as util from "./util.ts";let next_timerender_id = 0;export let display_time_zone = browser_time_zone();+export let display_tz = tz(display_time_zone);const formatter_map = new Map<string, Intl.DateTimeFormat>();@@ -33,6 +36,7 @@ export function clear_for_testing(): void {// Exported for testing only; we do not support live-updating the time zone.export function set_display_time_zone(time_zone: string): void {display_time_zone = time_zone;+ display_tz = tz(display_time_zone);formatter_map.clear();}@@ -137,7 +141,7 @@ export function get_localized_date_or_time_for_format(}// Exported for tests only.-export function get_tz_with_UTC_offset(time: number | Date): string {+export function get_tz_with_UTC_offset(time: Date): string {let timezone = new Intl.DateTimeFormat(user_settings.default_language, {timeZone: display_time_zone,timeZoneName: "short",@@ -154,7 +158,7 @@ export function get_tz_with_UTC_offset(time: number | Date): string {// show that along with (UTC+x:y)timezone = /GMT[+-][\d:]*/.test(timezone ?? "") ? "" : timezone;- const offset_minutes = Math.round(get_offset(time, display_time_zone) / 60000);+ 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")})`;@@ -190,7 +194,7 @@ export let render_now = (time: Date, today = new Date(), display_year?: boolean)// Presumably the result of diffDays will be an integer in this// case, but round it to be sure before comparing to integer// constants.- const days_old = difference_in_calendar_days(today, time, display_time_zone);+ const days_old = differenceInCalendarDays(today, time, {in: display_tz});if (days_old === 0) {time_str = $t({defaultMessage: "Today"});@@ -231,7 +235,7 @@ export function relative_time_string_from_date(date: Date): string {return $t({defaultMessage: "{minutes} minutes ago"}, {minutes});}- const days_old = difference_in_calendar_days(current_date, date, display_time_zone);+ const days_old = differenceInCalendarDays(current_date, date, {in: display_tz});const hours = Math.floor(minutes / 60);if (hours < 24) {@@ -271,7 +275,9 @@ export function last_seen_status_from_date(last_active_date: Date): string {return $t({defaultMessage: "Active {minutes} minutes ago"}, {minutes});}- const days_old = difference_in_calendar_days(current_date, last_active_date, display_time_zone);+ const days_old = differenceInCalendarDays(current_date, last_active_date, {+ in: display_tz,+ });const hours = Math.floor(minutes / 60);if (hours < 24) {@@ -333,15 +339,15 @@ export function initialize(): void {display_time_zone === undefined || // https://bugs.chromium.org/p/chromium/issues/detail?id=1487920display_time_zone === "Etc/Unknown" // https://bugs.chromium.org/p/chromium/issues/detail?id=1473422) {- display_time_zone = user_settings.timezone;+ set_display_time_zone(user_settings.timezone);try {new Intl.DateTimeFormat(undefined, {timeZone: display_time_zone});} catch {- display_time_zone = "UTC";+ set_display_time_zone("UTC");}}- last_update = start_of_day(new Date(), display_time_zone);+ last_update = startOfToday({in: display_tz});}function maybe_add_update_list_entry(entry: UpdateEntry): void {@@ -394,7 +400,7 @@ export function get_markdown_time_tooltip(reference: HTMLElement): DocumentFragm// This isn't expected to be called externally except manually for// testing purposes.export function update_timestamps(): void {- const today = start_of_day(new Date(), display_time_zone);+ const today = startOfToday({in: display_tz});if (!isEqual(today, last_update)) {const to_process = update_list;update_list = [];@@ -465,7 +471,7 @@ export function stringify_time(time: number | Date): string {export function format_time_modern(time: number | Date, today = new Date()): string {const hours = differenceInHours(today, time);- const days_old = difference_in_calendar_days(today, time, display_time_zone);+ const days_old = differenceInCalendarDays(today, time, {in: display_tz});if (time > today) {/* For timestamps in the future, we always show the year*/diff --git a/web/tests/lib/index.cjs b/web/tests/lib/index.cjsindex 8cf9e821d74..6027ed37ebc 100644--- a/web/tests/lib/index.cjs+++ b/web/tests/lib/index.cjs@@ -3,6 +3,7 @@const assert = require("node:assert/strict");const path = require("node:path");+require("@date-fns/tz"); // To prevent mockdate from interfering with itrequire("css.escape");require("handlebars/runtime.js");const {JSDOM} = require("jsdom");diff --git a/web/tests/time_zone_util.test.cjs b/web/tests/time_zone_util.test.cjsdeleted file mode 100644index b5a0579f87b..00000000000--- a/web/tests/time_zone_util.test.cjs+++ /dev/null@@ -1,95 +0,0 @@-"use strict";--const assert = require("node:assert/strict");--const {zrequire} = require("./lib/namespace.cjs");-const {run_test} = require("./lib/test.cjs");--const {get_offset, start_of_day, is_same_day, difference_in_calendar_days} =- zrequire("time_zone_util");--function pre(date) {- return new Date(date.getTime() - 1);-}--const ny = "America/New_York";-const ny_new_year = new Date("2023-01-01T05:00Z");-const ny_new_year_eve = new Date("2022-12-31T05:00Z");-const st_johns = "America/St_Johns";-const st_johns_dst_begin = new Date("2023-03-12T05:30Z");-const st_johns_dst_end = new Date("2023-11-05T04:30Z");-const chatham = "Pacific/Chatham";-const chatham_dst_begin = new Date("2022-09-24T14:00Z");-const chatham_dst_end = new Date("2023-04-01T14:00Z");-const kiritimati = "Pacific/Kiritimati";-const kiritimati_date_skip = new Date("1994-12-31T10:00Z");-const fractional_date = new Date("2023-01-02T03:04:05.678Z");--run_test("get_offset", () => {- assert.equal(get_offset(ny_new_year, "UTC"), 0);- assert.equal(get_offset(ny_new_year, ny), -5 * 60 * 60000);- assert.equal(get_offset(pre(st_johns_dst_begin), st_johns), -(3 * 60 + 30) * 60000);- assert.equal(get_offset(st_johns_dst_begin, st_johns), -(2 * 60 + 30) * 60000);- assert.equal(get_offset(pre(st_johns_dst_end), st_johns), -(2 * 60 + 30) * 60000);- assert.equal(get_offset(st_johns_dst_end, st_johns), -(3 * 60 + 30) * 60000);- assert.equal(get_offset(pre(chatham_dst_begin), chatham), (12 * 60 + 45) * 60000);- assert.equal(get_offset(chatham_dst_begin, chatham), (13 * 60 + 45) * 60000);- assert.equal(get_offset(pre(chatham_dst_end), chatham), (13 * 60 + 45) * 60000);- assert.equal(get_offset(chatham_dst_end, chatham), (12 * 60 + 45) * 60000);- assert.equal(get_offset(pre(kiritimati_date_skip), kiritimati), -10 * 60 * 60000);- assert.equal(get_offset(kiritimati_date_skip, kiritimati), 14 * 60 * 60000);- assert.equal(get_offset(fractional_date, "UTC"), 0);- assert.equal(get_offset(fractional_date, ny), -5 * 60 * 60000);- assert.equal(get_offset(fractional_date, kiritimati), 14 * 60 * 60000);-});--run_test("start_of_day", () => {- for (const [date, time_zone] of [- [pre(ny_new_year), "UTC"],- [ny_new_year, "UTC"],- [pre(ny_new_year), ny],- [ny_new_year, ny],- [pre(st_johns_dst_begin), st_johns],- [st_johns_dst_end, st_johns],- [pre(st_johns_dst_end), st_johns],- [st_johns_dst_end, st_johns],- [pre(chatham_dst_begin), chatham],- [chatham_dst_end, chatham],- [pre(chatham_dst_end), chatham],- [chatham_dst_end, chatham],- [pre(kiritimati_date_skip), kiritimati],- [kiritimati_date_skip, kiritimati],- ]) {- const start = start_of_day(date, time_zone);- assert.equal(- start.toLocaleDateString("en-US", {timeZone: time_zone}),- date.toLocaleDateString("en-US", {timeZone: time_zone}),- );- assert.equal(start.toLocaleTimeString("en-US", {timeZone: time_zone}), "12:00:00 AM");- }-});--run_test("is_same_day", () => {- assert.ok(is_same_day(pre(ny_new_year), ny_new_year_eve, ny));- assert.ok(!is_same_day(pre(ny_new_year), ny_new_year, ny));- assert.ok(is_same_day(pre(st_johns_dst_begin), st_johns_dst_begin, st_johns));- assert.ok(is_same_day(pre(st_johns_dst_end), st_johns_dst_end, st_johns));- assert.ok(is_same_day(pre(chatham_dst_begin), chatham_dst_begin, chatham));- assert.ok(is_same_day(pre(chatham_dst_end), chatham_dst_end, chatham));- assert.ok(!is_same_day(pre(kiritimati_date_skip), kiritimati_date_skip, kiritimati));-});--run_test("difference_in_calendar_days", () => {- assert.equal(difference_in_calendar_days(pre(ny_new_year), ny_new_year, ny), -1);- assert.equal(difference_in_calendar_days(pre(ny_new_year), ny_new_year_eve, ny), 0);- assert.equal(difference_in_calendar_days(ny_new_year, ny_new_year_eve, ny), 1);- assert.equal(difference_in_calendar_days(ny_new_year, pre(ny_new_year_eve), ny), 2);- assert.equal(difference_in_calendar_days(st_johns_dst_end, st_johns_dst_begin, st_johns), 238);- assert.equal(difference_in_calendar_days(chatham_dst_begin, chatham_dst_end, chatham), -189);-- // date-fns gives 2, but 1 seems more correct- assert.equal(- difference_in_calendar_days(kiritimati_date_skip, pre(kiritimati_date_skip), kiritimati),- 1,- );-});diff --git a/web/tests/timerender.test.cjs b/web/tests/timerender.test.cjsindex 0fc642c1b94..3159c8c338d 100644--- a/web/tests/timerender.test.cjs+++ b/web/tests/timerender.test.cjs@@ -27,7 +27,7 @@ function get_date(time_ISO, DOW) {const date_2017 = get_date("2017-05-18T07:12:53.000Z", "Thursday");// Check there is no UTC offset.-assert.equal(timerender.get_tz_with_UTC_offset(date_2017.getTime()), "UTC");+assert.equal(timerender.get_tz_with_UTC_offset(date_2017), "UTC");const date_2017_PM = get_date("2017-05-18T21:12:53.000Z", "Thursday");