1

I'm using date-fns in my React web app, and support multiple languages (English, French, and Spanish). I want to display the date in a way that makes sense to users of any of these three languages, and right now I do it like this:

import en from 'date-fns/locale/en';
import fr from 'date-fns/locale/fr';
import es from 'date-fns/locale/es';
import { format } from 'date-fns';
...
const locale = fr; // or en, or es
format(new Date(), 'MMMM d, yyyy h:mm a', { locale })

For English this gives April 14, 2023 1:40 PM

For French this gives avril 14, 2023 1:40 PM

For Spanish this gives abril 14, 2023 1:40 PM

The Problem: Even though this is translating the individual terms, it's still formatting them all the same way. I don't know if avril 14, 2023 1:40 PM is the correct order to put the terms in in French.

What I Want To Know: Is there a way to just print the date in a way that makes sense for the chosen language, rather than hard-coding a format?

gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • 1
    If you specify the format, then what else is date-fns to do but respect the format? `new Date().toLocaleString('es',{year:'numeric', month:'long', day:'numeric', hour:'numeric', minute:'numeric'})` returns something like "15 de abril de 2023, 21:23". Note that "locale" is a misnomer for language and there are a number of regional variants: AR, CL, CO, ES, MX, US. – RobG Apr 15 '23 at 11:25

0 Answers0