moments.js的奇怪行为

时间:2018-11-22 08:17:58

标签: javascript momentjs

var now = moment({ year: 2018, month: 11, day: 9 }).format('M');
alert(now);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>

预期的行为是警报显示“ 11”,但您可以看到显示“ 12”

有人知道为什么吗?

1 个答案:

答案 0 :(得分:3)

当输入格式为1到12时,月份的输入为0到11。

var now = moment({ year: 2018, month: 0, day: 9 }).format('M');

console.log(now);

now = moment({ year: 2018, month: 11, day: 9 }).format('M');

console.log(now);

now = moment({ year: 2018, month: 12, day: 9 }).format('M');

console.log(now);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>


Documentation about M format

enter image description here

Documentation about Month input

enter image description here



要以编程方式处理此案件,您既可以在设置月份时将其检索到月份中的1,也可以在最终显示中检索1。

示例:

var now = moment({ year: 2018, month: 11 - 1, day: 9 }).format('M');

console.log(now);


var now = String(Number(moment({ year: 2018, month: 11, day: 9 }).format('M')) - 1);

console.log(now);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>