Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Week wise Start and End date in angularjs

Before I am using angularjs-DatePicker from this npm.

Here,I am able to select the date from the date picker.But now I have to fields as FromDate and ToDate which means the week StartDate and EndDate should show when any date pick in that week.

Ex: Like in Calender 01-08-2017 Start on Tue, So whenever Selects Any date from 01 to 05 then the two fields should show as FromDate as 01 and TODate as 06 and in the same whenever the user selects the 31-07-2017 the the Two fields should show as 30 and 31 of july.

I have an idea to achieve the ToDate from FromDate Calender control onchange event in DotNet as like below mentioned code

Convert.ToDouble(objstart.DayOfWeek)).ToString("dd-MM-yyyy")

But how to achieve this usecase in the angularjs.

Thanks

like image 886
charan tej Avatar asked Aug 07 '17 06:08

charan tej


1 Answers

Ok, so what I'd do is to calculate different dates, and take the min/max depending on the start or end of the week.

Here:

//Use the date received, UTC to prevent timezone making dates shift 
var pickedDate = new Date("08-03-2017UTC");
 
var startSunday = new Date(pickedDate);
startSunday.setDate(pickedDate.getDate() - pickedDate.getDay());
var startMonth = new Date(pickedDate);
startMonth.setDate(1);
var startDate = Math.max(startMonth,startSunday);

console.log("Start:" , new Date(startDate));

var endSaturday = new Date(pickedDate);
endSaturday.setDate(pickedDate.getDate() + (7-pickedDate.getDay()));
var endMonth = new Date(pickedDate);
endMonth.setMonth(pickedDate.getMonth()+1);//Add a month
endMonth.setDate(0);// to select last day of previous month.
var endDate = Math.min(endMonth,endSaturday);

console.log("End" , new Date(endDate));

The trick was to play with the dates, find all the possible start and end dates, then choose the right one with Math.min and Math.max which will compare the dates using their timestamp.

like image 82
Salketer Avatar answered Oct 03 '22 22:10

Salketer