我想在javascript中获取两个日期之间的日历周差异。
示例:
a='09-May-2018'
b='14-May-2018'
这两个日历周的差异是2。
我开始将日期转换为瞬间,并通过Moment.js diff方法获得周数差异。但这是考虑7天为一周,并给我一个以上的例子。
我想到得到一周的时刻然后减去它。但在那,如果日期是两个不同的年份。我会得到错误的结果。与'01-Jan-2017'
和'01-Jan-2018'
一样,周数为1。
有没有更好的方法有效地做到这一点?
答案 0 :(得分:1)
获取一周的开始日期,并使用b1.diff(a1,'week');
function getWeekDiff(day1,day2){
var a1 = moment(day1, "DD-MMM-YYYY").startOf('week');
var b1 = moment(day2, "DD-MMM-YYYY").startOf('week');
var weekDiff = b1.diff(a1,'week');
console.log(weekDiff);
return weekDiff;
}
getWeekDiff("09-May-2018", "14-May-2018");
getWeekDiff("01-Jan-2017", "01-Jan-2018");
getWeekDiff("08-May-2018", "08-May-2018");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>
答案 1 :(得分:0)
您还可以在普通javascript中计算周差异。由于你还没有完全解释如何确定我做出一些猜测的周数的规则。以下内容:
1 + (endDate - startDate) / 7
仅当结束日期在开始日期之后才能正常工作。
/* Calculate weeks between dates
** Difference is calculated by getting date for start of week,
** getting difference, dividing and rounding, then adding 1.
** @param {Date} d0 - date for start
** @param {Date} d1 - date for end
** @param {number} [startDay] - default is 1 (Monday)
** @returns {number} weeks between dates, always positive
*/
function weeksBetweenDates(d0, d1, startDay) {
// Default start day to 1 (Monday)
if (typeof startDay != 'number') startDay = 1;
// Copy dates so don't affect originals
d0 = new Date(d0);
d1 = new Date(d1);
// Set dates to the start of the week based on startDay
[d0, d1].forEach(d => d.setDate(d.getDate() + ((startDay - d.getDay() - 7) % 7)));
// If d1 is before d0, swap them
if (d1 < d0) {
var t = d1;
d1 = d0;
d0 = t;
}
return Math.round((d1 - d0)/6.048e8) + 1;
}
console.log(weeksBetweenDates(new Date(2018, 4, 9), new Date(2018, 4, 14)));
答案 2 :(得分:0)
我有一个要求,如果差异大于12周,我必须采取一些行动。 所以我通过逐周()方法得到它。像这样:
Math.abs(endDate.diff(startDate, 'days'))<91 &&
Math.abs(startDate.week() - endDate.week()) < 12)
答案 3 :(得分:-1)
使用moment.js,根据https://momentjs.com/docs/#/durations/diffing/
/**
* @param fromDate - moment date
* @param toDate - moment date
* @return {int} diffInWeeks Diff between dates with weeks as unit
**/
const getDiffInWeeks = (fromDate, toDate) => {
const requestedOffset = 1
const diff = toDate.diff(fromDate);
const diffInWeeks = moment.duration(diff).as('weeks')
return Math.ceil(diffInWeeks) + requestedOffset
}