moment.js - 在法语中严格使用月份的缩写形式

moment.js - Use strictness on short form of month in French

我正在使用需要 moment.js 的 jquery 插件,因为我对它很陌生,这让我很困惑。

根据当时的js/doc和网上找的一些其他帖子,我理解如下:

(来自 http://momentjs.com/docs/

Moment's parser is very forgiving, and this can lead to undesired behavior. As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly.

moment('It is 2012-05-25', 'YYYY-MM-DD').isValid();        // true
moment('It is 2012-05-25', 'YYYY-MM-DD', true).isValid();  // false
moment('2012-05-25', 'YYYY-MM-DD', true).isValid();        // true

我们也可以同时使用语言和严格性:

moment('2012-10-14', 'YYYY-MM-DD', 'fr', true);

当我尝试使用法语语言环境时,moment('2012-10-14', 'YYYY-MM-DD', 'fr-ca', true) return 不正确。 (顺便说一句,如果您想知道,'fr-ca' 是加拿大法语语言环境。)

    var date = '1 févr. 2017'; // it means 1 Feb. 2017
    var format ='D MMM YYYY'; 

    var locale = 'fr-ca';

    moment.locale(locale);

// Problem starts here:
   moment(date, format, locale).isValid(); // return true as expected.
   moment(date, format, locale, true).isValid(); // return false, not expected.

我能想到的是可能"févr."不是"MMM"的格式。如果不是,那会是什么?

这是来自 moment-locale.js 源代码的法语缩写月份名称列表。

monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'

下面是我试过的完整版,请大家帮我看看哪里做错了。

https://jsfiddle.net/egcwzk2u/2/

提前致谢。

缩写中的句点(.)在使用默认的灵活解析时会被忽略,但在严格模式下字符串必须匹配格式exactly,并且它不是因为那个时期。

有两种选择:

  1. 您可以从输入字符串中删除句点。

    var date = '1 févr 2017';
    var format ='D MMM YYYY'; 
    
  2. 或者,您可以更改格式以允许句点:

    var date = '1 févr. 2017';
    var format ='D MMM. YYYY';