簡體   English   中英

Moment.js - moment()。format()創建無效日期?

[英]Moment.js - moment().format() creates invalid date?

moment().format()根據moment().isValid()創建一個無效的日期moment().isValid()

這是一個例子:

> moment.version
"2.14.1"
> moment.locale()
"fr"
> moment().format("ll")
"29 juill. 2016"
> moment("29 juill. 2016", "ll", true).isValid()
false

但是,如果我刪除該月的工作時間:

> moment("29 juill 2016", "ll", true).isValid()
true

或者,如果我禁用嚴格解析(刪除第3個參數),它可以工作:

> moment("29 juill. 2016", "ll").isValid()
true

為什么是這樣? 為什么moment().format("ll")創建一個有效的嚴格解析日期?

我認為這是因為"ll"不是一個有效的日期格式,如果你將運行moment函數並要求一個時間戳( .valueOf )你會得到一個NaN

moment("29 juill 2016", "ll", true).valueOf()
// NaN

您需要為第二個參數提供有效的格式,對於您的日期字符串,它將是"DD MMMM, YYYY"

此外,我認為你在juill有一個錯字,我認為它應該是juillet

moment.locale("fr")
// "fr"
 moment("29 july, 2016", "DD MMMM, YYYY", true).isValid()
// false
 moment("29 juillet, 2016", "DD MMMM, YYYY", true).isValid()
// true

如果其他人面臨同樣的問題,我自己回答這個問題。

這是由於moment.js版本2.8.1無法正確解析自定義短月份名稱的問題。 此問題已在更高版本2.14.1得到解決。

這是在2.8.12.14.1中產生不同結果的示例

moment.locale("fr", {
  monthsShort: [
    "janv.",
    "févr.",
    "mars",
    "avr.",
    "Mai",
    "juin",
    "juilltest.",
    "août",
    "sept.",
    "oct.",
    "nov.",
    "déc."
  ],
  monthsParseExact: true,
  longDateFormat: {
    LL: "DD MMM YYYY",
    ll: "DD MMM YYYY"
  },

});
console.log(moment.version);
moment.locale('fr');
console.log(moment.locale());
var testDate = '29 juilltest. 2016'; // month name with period in it that matches the custom short name given above
console.log(moment(testDate, "LL", true).isValid());
console.log(moment(testDate, "ll", true).isValid());
console.log(moment.localeData("fr"));

版本2.8.1: https //jsfiddle.net/3do4ubsj/

2.8.1
fr
false
false

版本2.14.1: https //jsfiddle.net/pkhcaqmy/

2.14.1
fr
true
true

修復它的提交: https//github.com/moment/moment/commit/fc5a352e9ca30e32a96875810604ad981d1442c3

moment.js repo中的相關問題: https//github.com/moment/moment/issues/3126

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM