How to subtract one month using moment.js?

JavascriptMomentjs

Javascript Problem Overview


I have a current month generated using moment().format('MMM YYYY'). I need to get last six months using this current month.

How to subtract one month using moment.js?

Javascript Solutions


Solution 1 - Javascript

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

> Before version 2.8.0, the moment#subtract(String, Number) syntax was > also supported. It has been deprecated in favor of > moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

> > As of 2.12.0 when decimal values are passed for days and months, they > are rounded to the nearest integer. Weeks, quarters, and years are > converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8

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
QuestionBhanuchandar ChallaView Question on Stackoverflow
Solution 1 - JavascriptDipiksView Answer on Stackoverflow