I'm trying to use Luxon.toLocaleString to format dates for different locales. I'm on Luxon version 3.0.1.
I'm following this example from the luxon documentation:
DateTime.now().toLocaleString({ locale: 'en-gb' }); //=> '20/04/2017'
My code:
import { DateTime } from 'luxon';
console.log(DateTime.fromISO('2017-04-20').toLocaleString({ locale: 'en-gb' }));
Running this gives me: 4/20/2017
, but the documentation linked above says it should be returning 20/04/2017
. It similarly is incorrectly returning the US format for other locales that I've tried.
The cause of my issue seems to be different than the one described in this question (missing Intl.DateTimeFormat implementation), because running the following code produces results that are consistent with having a proper Intl.DateTimeFormat installation:
const df = new Intl.DateTimeFormat('de', {day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC'});
console.log(df.format(new Date("2018-08-13T04:00:00.000Z")));
gives: 13. August 2018
as expected.
This is running in a React app (create-react-app), if that matters. (And the React app is served from Node 14, which I understand is supposed to come with full-icu
installed by default - although since this is running in the browser, I'm not sure if the Node version should matter)
CodePudding user response:
This is a misunderstanding of the Luxon documentation for toLocaleString.
The first formatOpts parameter is defined as:
formatOpts (any = Formats.DATE_SHORT) {Object} - Intl.DateTimeFormat constructor options and configuration options
The Intl.DateTimeFormat constructor options object is its second parameter and does not have a "locale" option. The language is set by its first parameter (misnamed "locale").
When using Luxon, to change the language used for the "locale", provide it as a parameter of the second opts argument.
There are no examples in the Luxon documentation that are consistent with the code in the OP. The only one that comes close is:
DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' });
which passes a default set of valid Intl.DateTimeFormat options as the first parameter and sets the language in the second options parameter (i.e. the reverse of Intl.DateTimeFormat parameter order).
Probably you want something like:
let DateTime = luxon.DateTime;
console.log(DateTime.fromISO('2017-04-20').toLocaleString(DateTime.DATE_SHORT, { locale: 'en-gb' }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"></script>