javascript - Compare dates on moment.js -


i working library moment.js difference in months between 2 dates .. code works fine .. takes month when same day eg: first date = 2017-08-14, second date = 2017-09-14 ... in case takes account full month, question ahy way if second date was: 2017-09-12 example .. take account month?

i leave little code have.

var date1 = moment('2017-08-14');  var date2 = moment('2017-09-12');  var result = date2.diff(date1, 'months');  console.log(result);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

according documentation .diff() round down when value positive, , round when value negative (i.e. positive values < 1 rounded down 0):

by default, moment#diff return number rounded towards 0 (down positive, negative). if want floating point number, pass true third argument.

if want floating point number, this:

var result = date2.diff(date1, 'months', true); 

and can apply own rounding up/down preference. if want round nearest month, use:

var result = math.round(date2.diff(date1, 'months', true)); 

var date1 = moment('2017-08-14');  var date2 = moment('2017-09-12');  var result = date2.diff(date1, 'months', true);  console.log(result);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

on related note, if want detect if a month boundary has been crossed between 2 dates (e.g. want 31st august 2017 vs 1st september 2017 counted 1 month difference because month changes august september), can extract month dates using .month() , calculate difference yourself:

var date1 = moment('2017-08-31');  var date2 = moment('2017-09-01');  var result = date2.month() - date1.month();  console.log(result);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -