Javascript .day() 使用 Moment.js 返回错误的月份日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28283351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:33:05  来源:igfitidea点击:

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

javascriptdatetimemomentjs

提问by Yaron Levi

I am using Moment.js to parse a string and get the day, month and year separately:

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

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

However, dayis not 25—it's 1. What is the correct API method?

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

回答by David Sherret

The correct function to use is .date():

要使用的正确功能是.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.

.day()给你星期几。这与日期对象上的javascript.getDate().getDay()函数类似。

If you want to get the month and year, you can use the .month()and .year()functions.

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

回答by Sébastien REMY

This how to get parts of date:

这是如何获取部分日期:

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! ');
}

回答by Muhamed Krasniqi

You can use moment().format('DD')to get the day of month.

您可以使用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.

Good Luck...

祝你好运...