Question

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);
Was it helpful?

Solution

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top