.day() returns wrong day of month with Moment.js
Asked Answered
M

4

84

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?

Mesentery answered 2/2, 2015 at 17:31 Comment(0)
B
173

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.

Boiler answered 2/2, 2015 at 17:33 Comment(3)
date.month() returns 11 instead of 12. It always returns -1 the entered month.Mesentery
@YaronLevi yeah, it's zero indexed. It talks about that in the documentation. The javascript date object does that too.Boiler
Wow that's confusing. They should just make 'day' represent day and then have a separate one for 'dayOfMonth'.Superiority
J
11

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...

Jehiel answered 26/9, 2019 at 14:25 Comment(0)
E
10

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! ');
}
Embrace answered 1/2, 2018 at 16:40 Comment(0)
B
1

.day(), is getting the day number of the week which output values ( 1 - 7 ) starting from Monday.

If the day is

  1. Monday will output 1
  2. Tuesday will output 2
  3. Wednesday will output 3
  4. Thursday will output 4
  5. Friday will output 5
  6. Saturday will output 6
  7. Sunday will output 7

To get the day of the month as @David mentioned, you need to use .date() Ex:

const today = moment().date()
Bought answered 18/6, 2022 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.