简体   繁体   English

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

[英].day() returns wrong day of month with Moment.js

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, day is not 25—it's 1. What is the correct API method?但是, day不是 25,而是 1。正确的 API 方法是什么?

The correct function to use is .date() :正确使用的函数是.date()

date.date() === 25;

.day() gives you the day of the week. .day()为您提供星期几。 This works similarly to javascript's .getDate() and .getDay() functions on the date object .这与日期对象上 javascript 的.getDate().getDay()函数类似。

If you want to get the month and year, you can use the .month() and .year() functions.如果要获取月份和年份,可以使用.month().year()函数。

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

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...祝你好运...

.day(), is getting the day number of the week which output values ( 1 - 7 ) starting from Monday. .day(),获取从星期一开始输出值(1-7)的星期几。

If the day is如果那天是

  1. Monday will output 1星期一将输出 1
  2. Tuesday will output 2星期二将输出 2
  3. Wednesday will output 3星期三将输出 3
  4. Thursday will output 4星期四将输出 4
  5. Friday will output 5周五将输出 5
  6. Saturday will output 6星期六将输出 6
  7. Sunday will output 7周日将输出 7

To get the day of the month as @David mentioned, you need to use .date() Ex:要获得@David 提到的月份中的某一天,您需要使用 .date() 例如:

const today = moment().date()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM