diff --git a/web_src/js/features/midnight.js b/web_src/js/features/midnight.js new file mode 100644 index 0000000000000..b48fd02725594 --- /dev/null +++ b/web_src/js/features/midnight.js @@ -0,0 +1,22 @@ +// Some timestamps are not meant to be localized in the user's timezone, only in their language. +// This is true for due date timestamps. These include a specific year, month, and day combination. If a user in one timezone +// sets the date YYYY-MM-DD, another user should see the same date, regardless of their timezone. So when a relative-time element +// has their datetime attribute specified only as YYYY-MM-DD, we will update it to YYYY-MM-DD midnight in the user's timezone. +// When the date is rendered, the only localization that will happen is the language. + +const dateRegex = /^\d{4}-\d{2}-\d{2}$/; + +// for all relative-time elements, if their datetime attribute is YYYY-MM-DD, we will update it to YYYY-MM-DD midnight in the user's timezone +export function initMidnightRelativeTime() { + const relativeTimeElements = document.querySelectorAll('relative-time[datetime]'); + + for (const element of relativeTimeElements) { + const datetimeAttr = element.getAttribute('datetime'); + + if (dateRegex.test(datetimeAttr)) { + const [year, month, day] = datetimeAttr.split('-'); + const userMidnight = new Date(year, month - 1, day); + element.setAttribute('datetime', userMidnight.toISOString()); + } + } +} diff --git a/web_src/js/index.js b/web_src/js/index.js index abf0d469d18ed..4da620c4d6dae 100644 --- a/web_src/js/index.js +++ b/web_src/js/index.js @@ -85,12 +85,14 @@ import {initRepoRecentCommits} from './features/recent-commits.js'; import {initRepoDiffCommitBranchesAndTags} from './features/repo-diff-commit.js'; import {initDirAuto} from './modules/dirauto.js'; import {initRepositorySearch} from './features/repo-search.js'; +import {initMidnightRelativeTime} from './features/midnight.js'; // Init Gitea's Fomantic settings initGiteaFomantic(); initDirAuto(); onDomReady(() => { + initMidnightRelativeTime(); initGlobalCommon(); initGlobalTooltips();