简体   繁体   English

从 Angular 的开始和结束日期获取周数

[英]Get weeks from start and end date in Angular

  1. Extract weeks from start date and end date - Donestart dateend date提取周 - 完成
  2. Week should be calculated from start date周应从start date计算
  3. Display weeks in this format (week start date)mm/dd - mm/dd(week end date) in dropdown.在下拉列表中以这种格式显示周(week start date)mm/dd - mm/dd(week end date)

Below code will get me the start and end date.下面的代码将为我提供开始和结束日期。

let dates = JSON.parse(localStorage.getItem('dates'));
let startDate = moment((dates[0].value)).format('YYYY-MM-DD'); //"2018-05-01"
let endDate = moment((dates[1].value)).format('YYYY-MM-DD'); //"2018-05-15"

Example Start date: Tuesday, May 1, 2018 End Day: Tuesday, May 15, 2018示例开始日期:2018 年 5 月 1 日,星期二 结束日期:2018 年 5 月 15 日,星期二

Total days is : 15 days.It as 2 weeks and 1 day.总天数是:15 天。它是 2 周和 1 天。

So i need to display a drop-down like below所以我需要显示一个像下面这样的下拉菜单

  • 05/01 - 05/07 (week1) 05/01 - 05/07(第 1 周)
  • 05/08 - 05/14 (week2) 05/08 - 05/14(第 2 周)
  • 05/15 - 05/15 (week3) 05/15 - 05/15(第 3 周)

Trying to extract the weeks试图提取周数

 Date.prototype.getWeek = function(start)
{
        //Calcing the starting point
    start = start || 0;
    var today = new Date(this.setHours(0, 0, 0, 0));
    var day = today.getDay() - start;
    var date = today.getDate() - day;

        // Grabbing Start/End Dates
    var StartDate = new Date(today.setDate(date));
    var EndDate = new Date(today.setDate(date + 6));
    return [StartDate, EndDate];
}

// test code
var Dates = new Date().getWeek();

But the above code doesn't work.但是上面的代码不起作用。 please help请帮忙

You can do following:您可以执行以下操作:

formatDates() {
    let startDate = moment('2018-05-01');
    let endDate = moment('2018-05-15');
    let weekData = [];
    while(startDate.isSameOrBefore(endDate)) {
        if(weekData.length > 0) {
            // Update end date
            let lastObj = weekData[weekData.length - 1];
            lastObj['endDate'] =  moment(startDate).format('MM/DD');
            lastObj['label'] = `${lastObj.startDate} - ${lastObj['endDate']} (week${weekData.length})`
            startDate.add(1, 'days');
        }
        weekData.push({startDate: moment(startDate).format('MM/DD')});
        startDate.add(6, 'days');
    }
    if(startDate.isAfter(endDate)) {
        // Update last object
        let lastObj = weekData[weekData.length - 1];
        lastObj['endDate'] =  moment(endDate).format('MM/DD');
        lastObj['label'] = `${lastObj.startDate} - ${lastObj['endDate']} (week${weekData.length})`
    }
    return weekData;
}

formatDates will return array of weeks as: formatDates将返回周数组:

[
    {startDate: "05/01", endDate: "05/07", label: "05/01 - 05/07 (week1)"},
    {startDate: "05/08", endDate: "05/14", label: "05/08 - 05/14 (week2)"},
    {startDate: "05/15", endDate: "05/15", label: "05/15 - 05/15 (week3)"}
]

If anyone is still looking for an easy solution here is mine:如果有人仍在寻找一个简单的解决方案,这里是我的:

shared.service.ts共享服务.ts

import * as moment from 'moment'; // Make sure you have installed moment from npm

  // Add these methods to your Service

  /**
   * @description group Array of dates by an entire week
   * @param dates Array of dates
   */
  public getWeeksMapped(dates: Date[]): Map<string, number[]> {
    const weeks = dates.reduce((week, date) => {
      const yearWeek = `${moment(date).year()}-${moment(date).week()}`;
      if (!week.has(yearWeek)) {
        week.set(yearWeek, []);
      }
      week.get(yearWeek).push(date.getTime()); // timestamp returned
      return week;
    }, new Map());

    return weeks;
  }


  /**
   * @description Returns the dates between 2 dates
   * @param startDate Initial date
   * @param endDate Final date
   * @param dayStep Day step
   */
  public getDateRange(startDate: Date, endDate: Date, dayStep = 1): Date[] {
    const dateArray = [];
    const currentDate = new Date(startDate);
    while (currentDate <= new Date(endDate)) {
      dateArray.push(new Date(currentDate));
      currentDate.setUTCDate(currentDate.getUTCDate() + dayStep);
    }
    return dateArray;
  }

component.ts组件.ts

const dates = this.sharedS.getDateRange(yourDateStart, yourDateEnd);
const weeksGrouped = this.sharedS.getWeeksMapped(dates);
console.log(weeksGrouped);

You will get the weeks Mapped properly.您将获得正确映射的周数。 The getWeeksMapped() returns as TimeStamp, however if you want to return as Date, just change the type in Map<string, Date[]> and remove the getTime() method while pushing the object. getWeeksMapped()作为 TimeStamp 返回,但是如果您想作为 Date 返回,只需更改Map<string, Date[]>并在推送对象时删除getTime()方法。 Like this:像这样:

  public getWeeksMapped(dates: Date[]): Map<string, Date[]> {
    const weeks = dates.reduce((week, date) => {
      const yearWeek = `${moment(date).year()}-${moment(date).week()}`;
      if (!week.has(yearWeek)) {
        week.set(yearWeek, []);
      }
      week.get(yearWeek).push(date); // remove getTime()
      return week;
    }, new Map());

    return weeks;
  }

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

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