JavaScript-set date to Friday before - javascript

I am using ASP.Net AJAX Calendar Extender to set a date in a textbox. Whilst it is simple enough to get the date from the user's selection in JavaScript, I am struggling to set the date in to a Friday.
In detail, what I am trying to do is for example, if a user selected a date which turns out to be a Tuesday, what I want to show in the textbox, is not that week's Friday, but the Friday before, i.e. the one that was 3 days before.
What I have achieved is to get the next Friday, i.e. the one coming up, but I have played around with the code in various ways to try and achieve what I want - can someone please help?
Thanks
dayToMtceSet = 5;
distance = (dayToMtceSet - currentDay) % 7;
toDate = toDate.setDate(toDate.getDate() + distance);
document.getElementById('<%= txtFromDate.ClientID%>').value = formatDate(toDate);
toDateSet = new Date(toDate);
toDateSet = toDateSet.setDate(toDateSet.getDate() + 6);
document.getElementById('<%= txtToDate.ClientID%>').value = formatDate(toDateSet);

With pure javascript jsFiddle:
if (date.getDay() === 5) {
console.log(date);
} else {
var beforeOneWeek = new Date(date.getTime() - 60 * 60 * 24 * 7 * 1000),
day = beforeOneWeek.getDay(),
diffToFriday = day > 5 ? 6 : 5 - day;
date.setDate((date.getDate() - 7) + diffToFriday);
console.log(date);
}
You could also use date.js
See jsFiddle
var date = Date.today();
if (date.getDay() === 5) {
date = Date.today();
} else {
date = date.moveToDayOfWeek(5, -1) // 5 is Friday, -1 is back one week
}

Related

How to find the current day of the year on the Julian calendar in Javascript

I've been toiling for days on how to calculate the current day of the year on the Julian calendar.
I have a function to get the current Julian Date (time since start of Julian period), and I have a function to get the Gregorian day of the year.
I haven't found any accurate answer, and my closest find was still 2 days behind what it should've been at the time.
I'd use this to find if there are any Julian calendar holidays currently.
I'd like to be able to get the day of the month, but I can figure that out later, and day of the year is top priority.
I have jQuery in use and available.
[edit:] Here are my functions so far:
Date.prototype.getJulianYearDate=function(){
var j=parseInt((this.getTime()-new Date('Dec 30,'+(this.getFullYear()-1)+' 23:00:00').getTime())/86400000).toString(),
i=3-j.length;
while(i-->0)j=0+j;
return j
}// source: https://www.webdeveloper.com/d/84211-javascript-and-julian-date/2
Date.prototype.getJulianDayNumber = function(Y = new Date().getYear(), M = new Date().getMonth() + 1, D = new Date().getDate()) {
var JDN = 367 * Y - (7 * (Y + 5001 + (M - 9) / 7)) / 4 + (275 * M) / 9 + D + 1729777;
return JDN;
//source of equation: https://en.wikipedia.org/wiki/Julian_day
}
Date.prototype.getJulianYearsSinceUnix = function() {
return new Date().getJulianDate() / 365.25;
}
// credit: https://stackoverflow.com/a/11760079
Date.prototype.getJulianDate = function(dateKind = new Date()) {
var julianUnix = dateKind.getTime() / 86400000 + 2440587.5;
return julianUnix;
}
If I just had the right equations, I am confident I could write the right functions, but for now I'm stumped

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
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

Future Date Calculator

I have the following script that when used, allows the user to see a future date, while excluding weekends. The problem i've encountered though is if the current day is Friday, and i set the future date to 3 days it counts the Saturday and Sunday as working days. I'm really hoping one of you may be able to help as I'm not really that great at Javascript.
The correct example would be: If Today = Friday then 3 working days from now would be Wednesday (not Monday as the script currently calculates it).
Any ideas?
var myDelayInDays = 3;
myDate=new Date();
myDate.setDate(myDate.getDate()+myDelayInDays);
if(myDate.getDay() == 0){//Sunday
myDate.setDate(myDate.getDate() + 2);//Tuesday
} else if(myDate.getDay() == 6){//Saturday
myDate.setDate(myDate.getDate() + 2);//Monday
}
document.write('' + myDate.toLocaleDateString('en-GB'));
Any help would really be great.
Thanks
Try this code by changing date and days to add, A custom loop is used to skip sat and sun
function addDates(startDate,noOfDaysToAdd){
var count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6){
//Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
count++;
}
}
return startDate;
}
var today = new Date();
var daysToAdd = 3;
alert(addDates(today,daysToAdd));

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/

How to cast a date column value in javascript, and how to increase this date variable?

I am using sharepoint 2013 online. I have created a custom list. On this list I have used JSLink to show an icon in a column. I would like to do some logic to show a red or a green icon. I have now in js 2 dates. The date from my column from the current item and the date of today. I would like to do the following check:
var contractEndDate = ctx.CurrentItem.Contract_x0020_einddatum;
var today = new Date();
if((contractEndDate + 10 days) > today)
{
return "<img src='https://myCompany.sharepoint.com/sites/teams/Sales/SiteAssets/green.png'/>";
}
else
{
return "<img src='https://myCompany.sharepoint.com/sites/teams/Sales/SiteAssets/red.png'/>";
}
How can I cast the var contractEndDate to a date? And how can I increase it with 10 days?
Add 10 and compare:
var endPlus10 = new Date(contractEndDate);
endPlus10.setDate(contractEndDate.getDate() + 10);
if (endPlus10 > today) ...
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC. You can compute the number of milliseconds in a day (see one_day variable) and compare dates.
See my JS Fiddle, http://jsfiddle.net/cVm59/1/
var contractEndDate = new Date("2-18-2014"),
today = new Date(),
one_day = 1000 * 60 * 60 * 24;
if((contractEndDate.getTime() + (one_day*10)) > today.getTime())
{
console.log("Less than 10 days ago");
}
else
{
console.log("More than 10 days ago");
}
This should be what you are looking for:
var contractEndDate = ctx.CurrentItem.Contract_x0020_einddatum;
var today = new Date();
var CED = new Date(contractEndDate);
CED.setDate(CED.getDate() + 10);
if(CED > today)
{
Create CED as a new date and then using the setDate this just adds 10 days before you make your comparison. You could clean this up and just set your contractEndDate as a new Date, but up to you.

Categories