S
S
softshape2018-05-15 08:00:17
JavaScript
softshape, 2018-05-15 08:00:17

How to get previous date with moment.js?

I'm trying to get a date like "previous August 1st" using moment.js. But there are no functions like "previous". Who has worked with moment.js, what is the most direct way out there to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gleip, 2018-05-15
@softshape

moment().add(-1, 'day').format(...)

S
Sergey Sokolov, 2018-05-15
@sergiks

I don’t use moment, so using pure JS you can create a date for now, set it to the desired day and month (August 1).
If the date is greater than now, subtract 1 year:

var D = new Date();
D.setDate(1);
D.setMonth(7);   // 0: Янв, 1: Фев, ... 7: Август
  D.setHours(12);  // опционально
  D.setMinutes(0); // опционально
  D.setSeconds(0); // опционально
if(D.getTime() > new Date().getTime()) D.setFullYear( D.getFullYear() - 1);

D.toString() // Tue Aug 01 2017 12:00:00 GMT+0300 (MSK)

// и можно из Даты создать объект moment:
var m = moment(D);

Surely, exactly the same trick can be done with the moment object itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question