簡體   English   中英

立即獲取從 2022 年開始的一年中幾周的所有開始和結束日期

[英]Get all the start and the end dates of weeks of a year starting 2022 in moment

我想立即以 YYYY-MM-DD (mysql) 格式獲取從 2022 年開始的一年中的所有開始和結束日期。

我希望最終結果看起來像這樣:

[
    ['2022-01-04', '2022-01-10'],
    ['2022-01-11', '2022-01-17'],
    ['2022-01-18', '2022-01-24'],
    // ...
    ['2022-12-24', '2023-01-01'],
    ['2023-01-02', '2023-01-08'],
    // ...
    ['2023-12-25', '2024-01-01'],
    // ...
    // Until the end of 2026
];

編輯 1:我嘗試了下面的代碼,但它失敗了:

const moment = require('moment');

const dateFormat = 'YYYY-MM-DD';
const dateToStart = '2022-04-11';
const dateToEnd = '2030-12-29';

function getWeeks() {
    const weeks = [];
    let currentDate = '2022-04-11';

    while (true) {

        if (currentDate === dateToStart) {
            weeks.push([dateToStart, moment(dateToStart, dateFormat).add(6, 'days').format(dateFormat)]);
        } else {
            weeks.push([
                moment(currentDate, dateFormat).add(1, 'days').format(dateFormat),
                moment(currentDate, dateFormat).add(6, 'days').format(dateFormat),
            ]);
        }
        currentDate = moment(dateToStart).add(6, 'days').format(dateFormat);

        if (currentDate === dateToEnd) break;
    }

    return weeks;
}

Momentjs 提供了一些非常有用的函數來獲得所需的 output。

  1. 創建 2 個時刻對象,開始和結束
  2. 循環,while end isAfter start
  3. 使用.startOf('isoWeek').endOf('isoWeek')獲取一周的范圍
  4. Append 到一個數組
  5. 設置開始時刻 object 向前 1 周: .add(1, 'week')

這個例子應該讓你開始,注意我已經降低了dateToEnd

 const dateFormat = 'YYYY-MM-DD'; const dateToStart = '2022-04-01'; const dateToEnd = '2023-12-29'; let weeks = []; let momsrt = moment.utc(dateToStart, dateFormat); let momend = moment.utc(dateToEnd, dateFormat); while (momend.isAfter(momsrt)) { weeks.push([ momsrt.startOf('isoWeek').format(dateFormat), momsrt.endOf('isoWeek').format(dateFormat) ]); momsrt.add(1, 'week'); } console.log(weeks);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.32/moment-timezone-with-data.min.js"></script>


足注:

請查看momentjs 項目狀態

長話短說:博士; 不要將它用於新項目,有更好的選擇。

暫無
暫無

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

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