I am using react and datefns.
I have the following code
import { enUS, ja } from 'date-fns/locale';
import { format, isValid, parseISO } from 'date-fns';
export const getDateLocal = (locale?: string) => {
switch (locale) {
case 'ja':
return ja;
case 'en':
default:
return enUS;
}
};
export const localizedDateFormatter = (
date: Date | number | string,
dateFormat = 'MMM dd',
locale = 'en'
): string => {
const dateIsIso = typeof date === 'string' ? isValid(parseISO(date)) : false;
if (!date || (!dateIsIso && !isValid(date))) {
return '-';
}
return format(new Date(date), dateFormat, { locale: getDateLocal(locale) });
};
I call this function like this
localizedDateFormatter(hoverFrom, 'MMM dd, yyyy', i18n.language) // can be ja or en
The problem is, the date is not converted like I would like.
ja: 12月 15, 2020
en: Dec 15, 2020
While it should be
ja: 2020年1月13日 (or at least 1月13日, 2020年)
en: Dec 15, 2020
Why so ?
I have not clue about japanese, so I can give an answer just looking at the source code, but maybe some japanese speaker could give a more precise answer.
You can check the locale source code here https://github.com/date-fns/date-fns/tree/master/src/locale/ja/_lib, but here are some insights I managed to discover.
DAY
The 日
character follows the day on its ordinal form (also it seems to be the name for Sunday). Look at here. So you need do
(ordinal day of month).
MONTH
The 月
character follows the month number when displaying the month's name (abbreviated or full). So if you use M
to display the month it won't show. You need MMM
or MMMM
. Compare JA with EN-US.
YEAR
The 年
character follows the year only if the date is in long format. This character is nowhere in this file, but it is here on the long and full date format (PPP
and PPPP
).
The japanese format that you are looking for is PPP
which shows dates like this:
The closest you can get to the format you where looking for is MMM do, yyyy
: