.day() returns 错误的日期 Moment.js

.day() returns wrong day of month with Moment.js

我正在使用 Moment.js 解析字符串并分别获取日、月和年:

var date = moment("12-25-1995", "MM-DD-YYYY");
var day = date.day();        

但是,day 不是 25,而是 1。正确的 API 方法是什么?

正确使用的函数是.date():

date.date() === 25;

.day() gives you the day of the week. This works similarly to javascript's .getDate() and .getDay() functions on the date object.

如果要获取月份和年份,可以使用.month() and .year()函数。

如何获取部分日期:

var date = moment("12-25-1995", "MM-DD-YYYY");

if (date.isValid()) {

    day = date.date(); 
    console.log('day ' + day);

    month = date.month() + 1;
    console.log('month ' + month);

    year = date.year(); 
    console.log('year '+ urlDateMoment.year());

} else {
    console.log('Date is not valid! ');
}

您可以使用 moment().format('DD') 获取月份中的第几天。

var date = +moment("12-25-1995", "MM-DD-YYYY").format('DD'); 
// notice the `+` which will convert 
// the returned string to a number.

祝你好运...