简体   繁体   English

立即获取从 2022 年开始的一年中几周的所有开始和结束日期

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

I want to get all the start and the end dates of weeks of a year starting 2022 in moment in YYYY-MM-DD (mysql) format.我想立即以 YYYY-MM-DD (mysql) 格式获取从 2022 年开始的一年中的所有开始和结束日期。

I want the end result to look something like this:我希望最终结果看起来像这样:

[
    ['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
];

EDIT 1: I tried the code below but it's failing:编辑 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 provide some really usefull functions to get the desired output. Momentjs 提供了一些非常有用的函数来获得所需的 output。

  1. Create 2 moment objects, the start and end创建 2 个时刻对象,开始和结束
  2. Loop, while end isAfter start循环,while end isAfter start
  3. Use .startOf('isoWeek') and .endOf('isoWeek') to get the range of a week使用.startOf('isoWeek').endOf('isoWeek')获取一周的范围
  4. Append that to an array Append 到一个数组
  5. Set the start moment object 1 week forward: .add(1, 'week')设置开始时刻 object 向前 1 周: .add(1, 'week')

This example should get you started, note that I've lowered the dateToEnd .这个例子应该让你开始,注意我已经降低了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>


Foot Note:足注:

Please see momentjs Project status请查看momentjs 项目状态

TL:DR;长话短说:博士; Don't use it for new projects, there are way better alternatives.不要将它用于新项目,有更好的选择。

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

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