javascript - moment.js accepts two digit month "01" when the format is M - Stack Overflow

Is the behavior correct when in strict mode, for format MDYYYY, moment.js will accept 01.09.2017? Sho

Is the behavior correct when in strict mode, for format M/D/YYYY, moment.js will accept 01.09.2017? Shouldn't it accept just 1.9.2017, if there is the only "one M" in the format? Same applies for D days.

Edit:

moment('1/09/2017', 'MM/D/YYYY', true).isValid() // false
moment('01/09/2017', 'M/D/YYYY', true).isValid() // true -> why? 

Why is M benevolent for 01, but MM is not for 1? Is it a bug?

Is the behavior correct when in strict mode, for format M/D/YYYY, moment.js will accept 01.09.2017? Shouldn't it accept just 1.9.2017, if there is the only "one M" in the format? Same applies for D days.

Edit:

moment('1/09/2017', 'MM/D/YYYY', true).isValid() // false
moment('01/09/2017', 'M/D/YYYY', true).isValid() // true -> why? 

Why is M benevolent for 01, but MM is not for 1? Is it a bug?

Share Improve this question edited Mar 13, 2017 at 14:52 mimo asked Mar 13, 2017 at 13:50 mimomimo 6,8678 gold badges47 silver badges57 bronze badges 2
  • Do you mean strict mode ? – Cody Geisler Commented Mar 13, 2017 at 14:03
  • Yes, thanks for correction. – mimo Commented Mar 13, 2017 at 14:07
Add a ment  | 

1 Answer 1

Reset to default 3

It could work not in correct way. In your example it works fine, but in other situation it could make a wrong result. Moment format doc

moment("01.09.2017", "M/D/YYYY").format("M/D/YYYY");
//"1/9/2017"
moment("02-25-1995", "MMM/D/YY").format("MM/DD/YYYY");
//"01/02/2025"

If you need to specify multiple formats, you can do it by set second argument as array of string formats. Moment multiple format

moment("29-06-1995", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]); // uses the last format
moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"]);          // uses the first format

For strict mode: this parameter effect to regular expression which parsing data and for number it will work correctly.

//Non strict regular    
Hb = /\d\d?/
//Strict regular
Sb = /\d\d/

d = b._strict;
case"MM":
case"DD":
case"YY":
case"GG":
case"gg":
case"HH":
case"hh":
case"mm":
case"ss":
case"ww":
case"WW":
   return d ? Sb : Hb;

In case with one letter always use non strict regular

case"M":
case"D":
case"d":
case"H":
case"h":
case"m":
case"s":
case"w":
case"W":
case"e":
case"E":
    return Hb;

So strict mode will fails in case

moment("1/9/1990", "MM/MD/YYYY", true).format("M/D/YYYY")
"Invalid date"

All this was test on momentjs version 2.7.0 In new version of moment 2.17.1 strict parameters used in formats ['MMM', 'MMMM'], ['dd', 'ddd', 'dddd']

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745649729a4638188.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信