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

JavascriptDatetimeMomentjs

Javascript Problem Overview


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

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?

Javascript Solutions


Solution 1 - Javascript

The correct function to use is .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.

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

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

Good Luck...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYaron LeviView Question on Stackoverflow
Solution 1 - JavascriptDavid SherretView Answer on Stackoverflow
Solution 2 - JavascriptSébastien REMYView Answer on Stackoverflow
Solution 3 - JavascriptMuhamed KrasniqiView Answer on Stackoverflow