Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get month name of last month using moment

I use the following code to get startDate and endDate of the last months.

// Previous month var startDateMonthMinusOne = moment().subtract(1, "month").startOf("month").unix(); var endDateMonthMinusOne   = moment().subtract(1, "month").endOf("month").unix();  // Previous month - 1  var startDateMonthMinusOne = moment().subtract(2, "month").startOf("month").unix(); var endDateMonthMinusOne   = moment().subtract(2, "month").endOf("month").unix(); 

How can i do to get also the month name ? (January, February, ...)

like image 502
wawanopoulos Avatar asked Feb 15 '17 09:02

wawanopoulos


People also ask

How do you find the month name with a moment?

This article goes in detailed on jquery moment get month from date. Let's see bellow example how to get month name from date in moment js. Here, i will give you simple example of jquery moment js get month name from date using format('MMMM').

How can I get last month from moment?

To get the previous month in moment js, use the subtract(1, "month") method to subtract the month in date and use format('MMMM') to get the month name from subtracted date. Just import moment in your file and call moment(). subtract(1, "month"). format('MMMM') and it will return previous month.

What is Moment () hour ()?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().

How do you subtract a month in a moment?

subtract(1, 'months'); but this does: moment("2017-12-01"). subtract(1, 'months'). format('MMMM DD h:mm A'); why the format is necessary?


Video Answer


2 Answers

Instead of unix() use the format() function to format the datetime using the MMMM format specifier for the month name.

var monthMinusOneName =  moment().subtract(1, "month").startOf("month").format('MMMM'); 

See the chapter Display / Format in the documentation

like image 160
NineBerry Avatar answered Oct 11 '22 13:10

NineBerry


You can simply use format('MMMM').

Here a working example:

var currMonthName  = moment().format('MMMM');  var prevMonthName  = moment().subtract(1, "month").format('MMMM');    console.log(currMonthName);  console.log(prevMonthName);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
like image 29
VincenzoC Avatar answered Oct 11 '22 14:10

VincenzoC