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

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

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.

There is very good Library available in JavaScript to handle Date Manipulations.
https://github.com/datejs/Datejs
There is a method
Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday')
Using these method you can get the start and ending date of the week based on the current week.
I hope that it will help.

You can simply achieve this using the library moment. There are a lot of useful functions in this library.
var selectedDate = moment('Mon Aug 10 2017');
//If you want to get the ISO week format(Monday to Sunday)
var weekStart = selectedDate.clone().startOf('isoweek').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('isoweek').format('MMM Do');
//If you want to get the Sunday to Saturday week format
var weekStart = selectedDate.clone().startOf('week').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('week').format('MMM Do');

No need angular directive here, you could use the JavaScript extension which is below.
//get week from date
Date.prototype.getWeekNumber = function (weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 0);//0 means friday
var firstDay = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstDay - target) / 604800000);;
};
//get date rance of week
Date.prototype.getDateRangeOfWeek = function (weekNo, weekstart) {
var d1 = this;
var firstDayOfWeek = eval(d1.getDay() - weekstart);
d1.setDate(d1.getDate() - firstDayOfWeek);
var weekNoToday = d1.getWeekNumber(weekstart);
var weeksInTheFuture = eval(weekNo - weekNoToday);
var date1 = angular.copy(d1);
date1.setDate(date1.getDate() + eval(7 * weeksInTheFuture));
if (d1.getFullYear() === date1.getFullYear()) {
d1.setDate(d1.getDate() + eval(7 * weeksInTheFuture));
}
var rangeIsFrom = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
return { startDate: rangeIsFrom, endDate: rangeIsTo }
};
Your code can be look like this
var startdate = '01-08-2017'
var weekList = [];
var year = startdate.getFullYear();
var onejan = new Date(year, 0, 1);//first january is the first week of the year
var weekstart = onejan.getDay();
weekNumber = startdate.getWeekNumber(weekstart);
//generate week number
var wkNumber = weekNumber;
var weekDateRange = onejan.getDateRangeOfWeek(wkNumber, weekstart);
var wk = {
value: wkNumber
, text: 'Week' + wkNumber.toString()
, weekStartDate: new Date(weekDateRange.startDate)
, weekEndDate: new Date(weekDateRange.endDate)
};
weekList.push(wk);

I guess there is no directive or filter for this, you need to create one for yourself. you can refer date object from date-time-object

Related

Javascript how to get full two year from current month?

I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}

How to get first and last day of current week when days are in different months?

For example, in the case of 03/27/2016 to 04/02/2016, the dates fall in different months.
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
The getDay method returns the number of the day in the week, with Sunday as 0 and Saturday as 6. So if your week starts on Sunday, just subtract the current day number in days from the current date to get the start, and add 6 days get the end, e.g.
function getStartOfWeek(date) {
// Copy date if provided, or use current date if not
date = date? new Date(+date) : new Date();
date.setHours(0,0,0,0);
// Set date to previous Sunday
date.setDate(date.getDate() - date.getDay());
return date;
}
function getEndOfWeek(date) {
date = getStartOfWeek(date);
date.setDate(date.getDate() + 6);
return date;
}
document.write(getStartOfWeek());
document.write('<br>' + getEndOfWeek())
document.write('<br>' + getStartOfWeek(new Date(2016,2,27)))
document.write('<br>' + getEndOfWeek(new Date(2016,2,27)))
You can find below solution for your problem.
let currentDate = new Date; // get current date
let first = currentDate.getDate() - currentDate.getDay();
var last = first + 6; // last day is the first day + 6
let firstDayWeek = new Date(currentDate.setDate(first)).toISOString();
var lastDayWeek = new Date(currentDate.setDate(last)).toISOString();
console.log(firstDayWeek, "first Day in week")
console.log(lastDayWeek, "end Day in week")
I like the moment library for this kind of thing:
moment().startOf("week").toDate();
moment().endOf("week").toDate();
You can try this:
var currDate = new Date();
day = currDate.getDay();
first_day = new Date(currDate.getTime() - 60*60*24* day*1000);
last_day = new Date(currDate.getTime() + 60 * 60 *24 * 6 * 1000);

how to write day from numbers in javascript?

How would I write this expression in JavaScript?
It is to represent a date that is 2 weeks, counted by each passing Thursday, but excludes the thursday of the week the date was made.
NeededDay = Today + (18 - DayOfWeek(today))
or since it is Wednesday, it could be written?
var date = new Date();
var NeededDate = date.getDay() + (18-3);
or
I wrote this but I do not know if it is right?
var value = 3;
var GivenDate = value;
var GivenDay = value.getDay();
var daysToSecondThursday = Givenday2.setDate(GivenDay + Givenday2.setDate(18 - GivenDay));
alert("two weeks after next thursday is = " + daysToSecondThursday.val());
what is the correct way? ?
You could use:
function GetThursdayIn2Weeks(date)
{
var day = date.getDay();
// Add 2 weeks.
var newDate = new Date(date.setTime(date.getTime() + (14 * 86400000)));
// Adjust for Thursday.
var adjust = 4 - day;
if (adjust <= 0) // Might need to be changed - See comments!
adjust +=7;
// Apply Thursday adjustment.
newDate = new Date(newDate.setTime(newDate.getTime() + (adjust * 86400000)));
return newDate;
}
If the date passed in is Thursday, then it will return two weeks from the following Thursday. If this is not what you want, then adjust the if (adjust <= 0) code above to be:
if (adjust < 0)
Here is a jsFiddle: http://jsfiddle.net/kgjertsen/ec7vnezn/

The day of the month does not show up properly in javascript (html)

This is my javascript code:
function borrowbook ()
{
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var input_day = document.getElementById("textbox").value;
var newday = today.setDate(day + input_day);
var fulltime1 = newday + "-" + month + "-" + year;
alert ("Return Date is: " + fulltime1);
}
And the result was not my expected result:
Actually what I want to do is if a user enters a value in 'Days allowed',I want to display the book return date.But I do not know why does the day of the month cannot show up properly.Any suggestion to solve this problem?
When you do:
var newday = today.setDate(day + input_day);
you are setting the value of newday to the return value of today.setDate(...), which is a time clip.
Since *input_day* is the value of a form control, and such values are always strings, the + operator will concatenate the values, not add them.
What you probably want is the date, so:
today.setDate(day + +input_day); // set the new date, converting input_date to Number
var newday = today.getDate(); // get the new date
Also, you should get the month and year after adding the day as it may change their values:
31 May + 1 day -> 1 June
There are three things you need to change.
Here is a working jsfiddle.
http://jsfiddle.net/bbankes/VMn3x/
First, the month and the year may also be incorrect. If today were 31-Dec 2014, your code would not show 10-Jan 2014, but instead 10-Dec 2013. You can rectify this by getting the day month and the year from the renew date instead of today's date.
Second, input_day is a string, so you need to parse it as an integer using the built-in javascript function parseInt();
Third, the setDate() method on a Date object does not return the new date. This is the problem that RobG shows.
The new function is as follows:
function borrowbook() {
var today = new Date();
var day = today.getDate();
var input_day = document.getElementById("textbox").value;
var returnDate = new Date();
returnDate.setDate(day + parseInt(input_day));
var returnDay = returnDate.getDate();
var returnMonth = returnDate.getMonth() + 1;
var returnYear = returnDate.getFullYear();
var fulltime1 = returnDay + "-" + returnMonth + "-" + returnYear;
alert ("Return Date is: " + fulltime1);
}

Cant assign value from getElementById to date?

I've got this:
var lDate = document.getElementById('txtLeaveDate');
var rDate = document.getElementById('txtReturnedDate');
Err...javascript so how do I assign the value of txtLeaveDate to a date variable
I tried:
var myDate = new Date(lDate.value);
But this assigns some long value....
I can do it if I try:
var today = new Date();
var day2 = new Date();
day2.setDate(today.getDate() + 30);
But the issue is I need to get the date from txtLeaveDate not by a date variable
edit complete code
var theLDate = new Date(lDate.value);
var theRDate = new Date(rDate.value);
//check if return date is a sunday, if it is no need
//to do anything,
//else make it a sunday
while (theRDate.getDay() != 0)
theRDate.setDate(theRDate.getDate() + 1);
//at this point RDate is a sunday...
while(theLDate.valueOf() <= theRDate.valueOf())
{
if(theLDate.getDay() == 0)
{ //sunday
var li = document.createElement('li');
li.setAttribute('id', ['liID' + count]);
var month = theLDate.getMonth();
var day = theLDate.getDate();
var year = theLDate.getFullYear();
var theDay = month + '/' + day + '/' + year + ' (Sunday)';
li.innerHTML = theDay;
ul.appendChild(li);
}
theLDate.setDate(theLDate.getDate() + 1);
count++;
}
But when I pick 2 dates in my calendar like so:
if I try that and say alert(theLDate.valueOf()); it returns
1309924800000
That's because that is the value of a Date object, measured in milliseconds since 1/1/1970 00:00:00, in this case corresponding to Wed Jul 6 04:00:00 2011 UTC.
Try using .toString() instead and you'll see the corresponding date in a human readable format.
The problem with your dates appearing to be in June is because the getMonth() function for odd reasons returns the month zero based, i.e. January == 0.
You need to use .innerHTML, otherwise you are not returning the text in the element.
var lDate = document.getElementById('txtLeaveDate').innerHTML;
var myDate = new Date(lDate);
document.write(myDate);
http://jsfiddle.net/jasongennaro/ua85k/
Months returned by the someDate.getMonth method are zero-indexed (from 0 to 11). So if using them to create a string add 1!
var month = theLDate.getMonth() + 1;

Categories