簡體   English   中英

如何獲得兩個時刻之間的日歷周差異?

[英]How to get the calendar week difference between two moments?

我想在 javascript 中獲取兩個日期之間的日歷周差異。

例子:

a='09-May-2018'
b='14-May-2018'

這兩者之間的日歷周差異是 2。

我首先將日期轉換為時刻,並通過 Moment.js diff 方法獲得以周為單位的差異。 但這是將 7 天視為一周,並在上面的示例中給我 1。

我想到了獲取時刻的周數然后減去它。 但是,如果日期是兩個不同的年份。 我會得到錯誤的結果。 '01-Jan-2017''01-Jan-2018'會將周數設為 1。

有沒有更好的方法來有效地做到這一點?

您還可以使用純 javascript 計算周差。 由於您還沒有完全解釋如何確定周數的規則,我做了一些猜測。 下列:

  1. 默認一周的第一天為星期一
  2. 復制日期並將它們移動到一周的開始
  3. 確保 d0 在 d1 之前
  4. 計算周數為1 + (endDate - startDate) / 7
  5. 可以使用可選的第三個參數設置一周的開始日期:0 = 星期日,1 = 星期一等。
  6. 結果總是積極的。 如果日期在同一周,則差值為 1。

這僅在結束日期晚於開始日期時才能正常工作。

 /* 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)));

我有一個要求,如果差異大於 12 周,我必須執行一些操作。 所以我通過獲取 Moment 的 Week by week() 方法來做到這一點。 像這樣:

Math.abs(endDate.diff(startDate, 'days'))<91 &&
  Math.abs(startDate.week() - endDate.week()) < 12) 

使用 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM