Search code examples
javascriptreactjsdate-fns

Localize date-fns


I had a working solution for date-fns using the following:

const formatMonth = format("MMM");

Then I imported the locale and tried the following:

import { de } from 'date-fns/locale';

const formatMonth = format("MMM", {locale: de});

Getting the error: RangeError: Invalid time value. How do I change the language to german? The docs kinda suggest exactly the same, but it's not working.

EDIT: Maybe that is relevant and showcases, why the new Date() is not necessary for the format:

const months = eachMonthOfInterval({
    start: startOfYear(value),
    end: endOfYear(value)
});
{months.map((month) => (
   <ListboxOption
     key={month.toDateString()}
     value={month}
     date={formatMonth(month)}
     disabled={!isOlderThen18Years(month)}
   ></ListboxOption>
))}

Also, this code works in code sandbox, but won't in my react application. Still throwing an error: RangeError: Invalid time value.

import { format } from 'date-fns';
import { de } from 'date-fns/locale';

const date = new Date();

console.log( format(
  date, 'MMM', 
{ awareOfUnicodeTokens: true, locale: de}
) );

Solution

  • As you are using the FP version to format a date you need to use the formatWithOptions function to pass the locale options.

    import format from "date-fns/fp/formatWithOptions";
    

    It has a slightly different function signature then the format function, where you need to pass the options as the first argument.

    const formatMonth = format({ locale: de }, "MMM");
    

    Edit happy-hill-2e0mb