23

I'm sure this is a simple thing but I haven't been able to find the specific syntax in any of the documentation or in any related posts.

In order to get a month-picker to work i need to instantiate a new Date object when my controller initializes.

Controller

scope.date = new Date();

This creates a date object with the following format:

Mon Feb 01 2016 15:21:43 GMT-0500 (Eastern Standard Time)

However when I attempt to pull the month from the date object, using moment, I get the error:

enter code here

getMonth method

var month = moment().month(scope.date, "ddd MMM DD YYYY");

Any idea how to pull the month from the above date object without using substring?

NealR
  • 10,189
  • 61
  • 159
  • 299

3 Answers3

52

You can use moment.month() it will return or set the value.

moment.month() is zero based, so it will return 0-11 when doing a get and it expects a value of 0-11 when setting passing a value in.

var d = moment(scope.date);
d.month(); // 1
d.format('ddd MMM DD YYYY'); // 'Mon Feb 01 2016'
peteb
  • 18,552
  • 9
  • 50
  • 62
  • Even if I change the statement to `var month = moment().month(scope.date);` I still get the `Invalid Date` error – NealR Jul 11 '16 at 19:36
  • You can't set `moment.month()` to a value outside of 0-11, otherwise it won't be a valid month. You're trying to pass a whole date into it. Just create the date with `var d = moment(scope.date)` and then access the month by using `d.month()` – peteb Jul 11 '16 at 19:36
5

As moment.month() returns zero based month number you can use moment.format() to get the actual month number starting from 1 like so

moment.format(scope.date, 'M');

Mawcel
  • 1,967
  • 15
  • 22
1

You can use moment(scope.date).format("M");

Adrian
  • 21
  • 3