Thursday, 21 January 2021

datefns format is not completely formatted

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 ?



from datefns format is not completely formatted

No comments:

Post a Comment