0

I need to have the following functionality in moment js, for my app.

var nDay = moment(2007, 0, 28).next('date'); //--> 2007-0-29T00:00:00.00
var pDay = moment(2007, 0, 28).previous('date'); //--> 2007-0-27T00:00:00.00

Similarly:

.next('week'), .next('month')

and gets the particular date back.

I know momentjs has manipulation methods, but using them is a pain as it mutates the original. Even with the .clone(), it's not easy.

So guys, how to implement this next(), and previous() methods, in moment or in js?

Or, what is the easiest way to find the day after a particular day?

VincenzoC
  • 30,117
  • 12
  • 90
  • 112
ISONecroMAn
  • 1,460
  • 2
  • 16
  • 23
  • 1
    Checkout the moment docs - read through them and see if you can find what you need. They have covered almost everything. Start out at the [duration](http://momentjs.com/docs/#/durations/add/) section. – Ryan Wheale Aug 27 '16 at 19:25
  • 1
    Possible duplicate of [Incrementing a date in JavaScript](http://stackoverflow.com/questions/3674539/incrementing-a-date-in-javascript) – 4castle Aug 27 '16 at 19:25
  • duration, used with add(), and subtract(), is not giving me the result i want. Also it mutates the original. So, it can be done with some formating and stuff. – ISONecroMAn Aug 27 '16 at 19:33

1 Answers1

2

As you said in the question, you can use moment manipulation functions like add and subtract along with clone to avoid original object mutation.

To add a custom function to moment use moment.fn.

Moment manipulation functions accept 'months', 'weeks', 'days' etc as parameter, while it seems that you want to use 'month', 'week', 'date', so you need to convert your input strings to moment equivalent.

Here there is a working example:

moment.fn.next = function(unit){
  // Convert input to strings used by moment
  unit = unit === 'date' ? 'days' : unit;
  if( unit === 'month' || unit === 'week'){
    unit += 's';
  }
  
  return this.clone().add(1, unit);
}

moment.fn.previous = function(unit){
  // Convert input to strings used by moment
  unit = unit === 'date' ? 'days' : unit;
  if( unit === 'month' || unit === 'week'){
    unit += 's';
  }
  
  return this.clone().subtract(1, unit);
}

var nDay = moment([2007, 0, 28]).next('date');
var pDay = moment([2007, 0, 28]).previous('date');
var nMonth = moment([2007, 0, 28]).next('month');
console.log(nDay.format());
console.log(pDay.format());
console.log(nMonth.format());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112