Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to localize formatDuration #3752

Open
hayata-suenaga opened this issue Apr 2, 2024 · 1 comment
Open

How to localize formatDuration #3752

hayata-suenaga opened this issue Apr 2, 2024 · 1 comment

Comments

@hayata-suenaga
Copy link

I want to localize the string returned by formatDuration.

formatDuration takes an option object that has locale field. However, this field is an object typed as Pick<Locale, "formatDistance">. The locale object needs to have the formatDistance method.

I want to localize the durations string with just the language code. Is there a way to achieve this?

@sumodmatto
Copy link

sumodmatto commented Apr 17, 2024

@hayata-suenaga

Importing the locale object that includes the formatDistance property and using it directly is indeed a viable approach. Alternatively, if you prefer using string identifiers for locales, you could consider mapping these strings to their corresponding locale objects.

Here’s how you can implement it using date-fns:

import { enUS, fr, de, ja } from "date-fns/locale";
import { formatDuration } from "date-fns";

const locales = {
  en: enUS,
  fr: fr,
  de: de,
  ja: ja,
};

// Example usage:
const duration = { years: 1, months: 6 };
const languageCode = "ja";
const options = { locale: locales[languageCode] };
const output = formatDuration(duration, options);
console.log(output); // Outputs the duration in Japanese

This approach provides a flexible and straightforward way to utilize different locales by referring to them through language codes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants