Skip to content
Advertisement

How can I subtract 1 month using moment.js?

I want to subtract 1 month from a given date in (DD/MM/YYYY) format, but when I do that using moment.js, it gives me the result as 01/12/2020. How can I resolve this? Basically when I click on the left-arrow, the month should be subtracted by 1 every

enter image description here

var startOfMonth = moment().clone().startOf('month').format('DD/MM/YYYY');

leftArrow.on('click', function(){
    var start = moment(startOfMonth).subtract(1, 'months').format("DD/MM/YYYY");
});

Advertisement

Answer

How can I subtract one month using moment.js?

tl,dr;

moment(date).add(-1, 'months');
// or:  moment(date).subtract(1, 'months');

initial answer:

Here’s a basic example.

It stores the date as a moment object, which you then modify by adding or subtracting a month without ever caring what its current value is. You could also store it as a JavaScript Date object, which is useful when you have to communicate it to an external entity (a db, the browser, etc…).

Take away points:

  • the date is not stored as text
  • the mods to the date are minimal
  • the date is parsed to text in only one place: before updating DOM (in setDate function)

// set initial date
let storedDate = moment.now();

// update DOM
setDate(storedDate);

function setDate(date) {
  document.getElementById('text').innerText = moment(date).format('MMMM YYYY');
}

function addMonths(months) {
  // change stored date
  storedDate = moment(storedDate).add(months, 'months');

  // update DOM
  setDate(storedDate);
}
#text {
  min-width: 120px;
  text-align: center;
  display: inline-block
}
button {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

<div>
  <button onclick="addMonths(-1)">&lt;</button>
  <span id="text"></span>
  <button onclick="addMonths(1)">&gt;</button>
</div>

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement