arunkumar
arunkumar

Reputation: 353

Get weeks from start and end date in Angular

  1. Extract weeks from start date and end date - Done
  2. Week should be calculated from start date
  3. Display weeks in this format (week start date)mm/dd - mm/dd(week end date) in dropdown.

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

Total days is : 15 days.It as 2 weeks and 1 day.

So i need to display a drop-down like below

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

Upvotes: 1

Views: 5534

Answers (2)

rick
rick

Reputation: 567

If anyone is still looking for an easy solution here is mine:

shared.service.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

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. 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;
  }

Upvotes: 0

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

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:

[
    {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)"}
]

Upvotes: 3

Related Questions