Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Full Weeks and Days between a Date Range using moment.js

My date range is

var currDay = Jan.1
var birthday = Feb.15

I know that to find the difference in number of weeks is

currDay.diff(birthday, 'week')

However, is there a way to find the full weeks and the remaining days?

like image 738
lost9123193 Avatar asked Nov 01 '25 07:11

lost9123193


1 Answers

You can make use of duration.

You can get the years, months (excludes years) and days (excludes years and months) using this. Only problem is weeks are calculated using the value of days so you'd still have to get the remainder on days if you're getting the number of weeks.

From momentjs docs:

Pay attention that unlike the other getters for duration, weeks are counted as a subset of the days, and are not taken off the days count.

Note: If you want the total number of weeks use asWeeks() instead of weeks()

var currDay = moment("2018-01-01");
var birthday = moment("2018-02-16");

var diff = moment.duration(birthday.diff(currDay));

console.log(diff.months() + " months, " + diff.weeks() + " weeks, " + diff.days()%7 + " days.");

console.log(Math.floor(diff.asWeeks()) + " weeks, " + diff.days()%7 + " days.");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
like image 159
H77 Avatar answered Nov 02 '25 20:11

H77



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!