Get Date Of Specific Day Of The Week In Javascript
Solution 1:
functionnextSession(date) {
var ret = newDate(date||newDate());
ret.setDate(ret.getDate() + (3 - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
This one will set date to next Wednesday. If it is already Wednesday, result will be one week later from given date.
EDIT: Added possibility of calling function without a parameter: nextSession()
- it returns next session date from today
Solution 2:
Solution 3:
If you just need wednesday, you should be able to do something like this:
functionnext(today) {
var offset = (today.getDay() < 3) ? 0 : 7;
var daysUntilWednesday = 3 + offset - today.getDay();
returnnewDate().setDate(today.getDate() + daysUntilWednesday);
}
var wed = next( newDate() );
EDIT:
or something like this? http://jsfiddle.net/zy7F8/1/
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
functionnext(day) {
var today = newDate();
var today_day = today.getDay();
day = day.toLowerCase();
for (var i = 7; i--;) {
if (day === days[i]) {
day = (i <= today_day) ? (i + 7) : i;
break;
}
}
var daysUntilNext = day - today_day;
returnnewDate().setDate(today.getDate() + daysUntilNext);
}
// insert a week dayalert(newDate(next( "Wednesday" )));
EDIT: Made a correction for days entered that are yet to come in the same week.
Solution 4:
Here you go: http://jsfiddle.net/ePQuv/
The js (no jQuery needed) is:
functionaddDays(myDate,days) {
returnnewDate(myDate.getTime() + days*24*60*60*1000);
}
functionsubtractDays(myDate,days) {
returnnewDate(myDate.getTime() - days*24*60*60*1000);
}
functiondateOfNext(weekdayNumber) {
var today = newDate();
var lastSunday = subtractDays(today, today.getDay());
var daysToAdd = weekdayNumber;
if (weekdayNumber <= today.getDay()) {
daysToAdd = daysToAdd + 7;
}
returnaddDays(lastSunday, daysToAdd);
}
What this does is subtract the current day of the week from the current date, to get to last sunday. Then, if today is after or equal to the "next day" you're looking for it adds 7 days + the day of the week that you want to get to, otherwise it just adds the day of the week. This will land you on the next of any given weekday.
Solution 5:
Here is a function to return the next day number.
functionnextDay(dayNb){
returnfunction( date ){
returnnewDate(date.getTime() + ((dayNb-date.getDay() +7) %7 +1) *86400000);
};
}
To use it, set the day number you want 0: Mon - 6: Sun
var nextWed = nextDay(2);
alert( nextWed( newDate() ));
Post a Comment for "Get Date Of Specific Day Of The Week In Javascript"