简体   繁体   English

使用 moment.js 查找日期范围之间的完整周和天

[英]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?但是,有没有办法找到完整的周数和剩余的天数?

You can make use of duration .您可以使用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 :momentjs 文档

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()注意:如果您想要总周数,请使用asWeeks()而不是asWeeks() 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>

 var currDay = moment("Jan.1","MMM.DD"); var birthday = moment("Feb.15","MMM.DD"); var diff = moment.duration(birthday.diff(currDay)); console.log(diff.weeks() +" weeks & "+ diff.days()%7 +" days to go for birthday");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM