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

时间:2018-03-22 07:50:58

标签: javascript momentjs

我的日期范围是

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

我知道找到周数的差异是

currDay.diff(birthday, 'week')

但是,有没有办法找到整周和剩余的几天?

2 个答案:

答案 0 :(得分:0)

您可以使用duration

您可以使用此获取年份,月份(不包括年份)和天数(不包括年份和月份)。唯一的问题是使用天数值来计算周数,因此如果您获得周数,您仍需要在天数内获得余数。

来自momentjs docs:

  

请注意,与其他吸气剂不同,持续时间为数周   算作天数的一个子集,并且不计算天数。

注意:如果您希望总周数使用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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
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");
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
&#13;
&#13;
&#13;