facebook / docusaurus

Easy to maintain open source documentation websites.
https://docusaurus.io
MIT License
56.3k stars 8.45k forks source link

i18n: allow to provide DateTimeFormat calendar #5440

Closed slorber closed 2 years ago

slorber commented 3 years ago

🐛 Bug Report

    new Intl.DateTimeFormat("fa", {
      day: 'numeric',
      month: 'numeric',
      year: 'numeric',
      timeZone: 'UTC',
    }).format(new Date()).replace(/[۰-۹]/g, (chr) => {
      const persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']
      return persian.indexOf(chr)
    })

This code does not use the same calendar on Node.js (Gregorian) and browsers (Solar Hijri), leading to a different date being rendered in SSR and after React hydration.

We should provide an i18n locale option to force a given calendar and make sure the formatted date is consistent between SSR/client.

    new Intl.DateTimeFormat("fa", {
      day: 'numeric',
      month: 'numeric',
      year: 'numeric',
      timeZone: 'UTC',
      calendar: "gregory"
    }).format(new Date()).replace(/[۰-۹]/g, (chr) => {
      const persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']
      return persian.indexOf(chr)
    })

Issue initially reported here: https://github.com/facebook/docusaurus/pull/5410#issuecomment-906529751

Josh-Cena commented 2 years ago

@slorber I've justed worked a bit on this. While it's useful to add another calendar config option, I wonder why would React hydration ever lead to a different result? Isn't the date always formatted on the server-side?

slorber commented 2 years ago

hmm yes it may not be a SSR problem in the end, can't be sure anymore 😅

It could also be related to different Node.js versions using different calendars for the same locale.

Maybe this is not an issue anymore since NodeJS has better Intl support, but it might still be useful to provide a calendar as an option 🤷‍♂️ we have seen some users don't like to use BCP47 codes for locale keys as it leads to complicated FS paths