Katharina Schreiber
Katharina Schreiber

Reputation: 1371

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}
) );

Upvotes: 3

Views: 33012

Answers (2)

knoefel
knoefel

Reputation: 6989

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

Upvotes: 4

Abheeth Kotelawala
Abheeth Kotelawala

Reputation: 142

You need to pass the Date as the first Parameter. For an example,

const formatMonth = format(new Date(),"MMM", {locale: de}); <br>

OR

const formatMonth = format(new Date(10/28/2021),"MMM", {locale: de});

enter image description here

Upvotes: 2

Related Questions