Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Moment to get month of Date object

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?

like image 833
NealR Avatar asked Jul 11 '16 19:07

NealR


People also ask

How do you find the month from a date with a moment?

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

How do you use moments to date?

moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format. This example formats a date as a four-digit year, followed by a hyphen, followed by a two-digit month, another hyphen, and a two-digit day.

How do you find the month in string in a moment?

You can simply use format('MMMM') .


2 Answers

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'
like image 110
peteb Avatar answered Oct 19 '22 14:10

peteb


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

like image 3
Mawcel Avatar answered Oct 19 '22 16:10

Mawcel