简体   繁体   English

datefns 格式未完全格式化

[英]datefns format is not completely formatted

I am using react and datefns.我正在使用 react 和 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我这样称呼这个 function

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?为什么这样?

DISCLAIMER免责声明

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.您可以在此处查看语言环境源代码https://github.com/date-fns/date-fns/tree/master/src/locale/ja/_lib ,但这里有一些我设法发现的见解。

DAY

Thecharacter 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).所以你需要do (每月的序数天)。

MONTH

Thecharacter 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.因此,如果您使用M显示月份,它将不会显示。 You need MMM or MMMM .你需要MMMMMMM Compare JA with EN-US .JAEN-US进行比较。

YEAR

Thecharacter 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 ).这个字符在这个文件中没有,但它长日期格式( PPPPPPP )中。


The japanese format that you are looking for is PPP which shows dates like this:您正在寻找的日文格式是PPP ,它显示如下日期:

  • EN : February 15th, 2020 CN : 2020 年 2 月 15 日
  • JA : 2020年2月15日JA : 2020年2月15日

The closest you can get to the format you where looking for is MMM do, yyyy :最接近您要查找的格式是MMM do, yyyy

  • EN : Feb 15th, 2020 CN : 2020 年 2 月 15 日
  • JA : 2月 15日, 2020 JA : 2020 年 2 月 15 日

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM