22

I think i'm mainly having a brain fart. I just want to fast forward a Date() until a specific day of the week and then get the Month, Day, Year for that.

E.g. today is 09/03/10 but i want a function (nextSession()) to return 09/08/10 (next wednesday).

How would I do this? The best thing I can think of is add a day to setDate() until getDay() == 3, but it's sorta ugly...

P.S. jQuery is cool too.

Oscar Godson
  • 31,662
  • 41
  • 121
  • 201

7 Answers7

32
function nextSession(date) {
    var ret = new Date(date||new Date());
    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

pepkin88
  • 2,742
  • 20
  • 19
  • Modified it to: function xnextSession() { var ret = new Date(); ret.setDate(ret.getDate() + (3 - 1 - ret.getDay() + 7) % 7 + 1); return ret; } That'll still work right? I mean... seems like it would... – Oscar Godson Sep 03 '10 at 20:10
  • I see you have changed `var ret = new Date();` It must be `new Date(date)`, because setDate() will set only day of month, and other information like month or year are gone. The reason why I declare variable ret is because I don't want to change value `date`. `var ret = new Date(date)` makes copy of object `date`, not copy of reference. EDIT: I'm sorry, of course it will work for current day, I didn't see everything ^^' – pepkin88 Sep 03 '10 at 20:20
  • Damn, this is clean. My only suggestion would be to make the day you're advancing to a parameter. +1 – Ender Sep 03 '10 at 20:26
  • I also can't believe you actually used the % (mod) operator! – Oscar Godson Sep 03 '10 at 20:32
  • Sure, would be perfect. Anyway I decided to bind this to Wednesday, because of name of function "nextSession", which I guess indicates Wednesday. – pepkin88 Sep 03 '10 at 20:36
8

Use the DateJS library.

Date.parse('next wednesday');
Adam
  • 43,763
  • 16
  • 104
  • 144
  • @Adam thanks, looks perfect, but im going to wait to see if someone gives me a lighter weight way of doing it. 25k + jQuery + jQuery UI + my personal 40kb JS file for this app is pretty heavy haha But, this is a very cool lib – Oscar Godson Sep 03 '10 at 19:30
  • @Oscar - That is about as lightweight as you're going to get given what you are looking to do. However, have you checked out the minification of your Javascript? If you're not doing that, you definitely should be. Check out YUI compressor or Google Closure. Both will compress your Javascript to *much* smaller levels. – JasCav Sep 03 '10 at 19:50
  • @Oscar - Actually...you don't need jQuery-UI for DateJS. And, if you are using jQuery-UI, you already have the overhead of jQuery. DateJS really adds nothing. 25kb is nothing (especially compared to the size of a single image). – JasCav Sep 03 '10 at 19:52
  • @Jason i know i dont need jQuery UI for DateJS :) I have it for date pickers and things. And see answer below. Thats *way* more lightweight than: http://www.datejs.com/build/date.js just to get next wednesday's date. And it's not the actual file size that worries me, its the processing time in IE8 (and slightly worries me in Firefox 3.5) and thanks, ill probably compress it once it goes into production. Thanks! – Oscar Godson Sep 03 '10 at 20:00
  • @Oscar - Ah. Didn't realize all you needed was next Wednesday. :-) I thought you were requiring something more generic. Natural language problems strike again! Glad you got your answer. – JasCav Sep 03 '10 at 21:00
6

If you just need wednesday, you should be able to do something like this:

function next(today) {
    var offset = (today.getDay() < 3) ? 0 : 7;
    var daysUntilWednesday = 3 + offset - today.getDay();
    return new Date().setDate(today.getDate() + daysUntilWednesday);
}

var wed = next( new Date() );

EDIT:

or something like this? http://jsfiddle.net/zy7F8/1/

var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

function next(day) {

    var today = new Date();
    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;

    return new Date().setDate(today.getDate() + daysUntilNext);

}

// insert a week day
alert(new Date(next( "Wednesday" )));​​​​​​​​​

EDIT: Made a correction for days entered that are yet to come in the same week.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • Just a comment; the for loop could be replaced with `indexOf` I know the loop is fast and small, but I think it makes it easier to read. Also, the function should check if the day is the day and throw an error if it is not. – nycynik Aug 23 '21 at 13:47
2

Here you go: http://jsfiddle.net/ePQuv/

The js (no jQuery needed) is:

function addDays(myDate,days) {
    return new Date(myDate.getTime() + days*24*60*60*1000);
}

function subtractDays(myDate,days) {
    return new Date(myDate.getTime() - days*24*60*60*1000);
}

function dateOfNext(weekdayNumber) {
    var today = new Date();

    var lastSunday = subtractDays(today, today.getDay());

    var daysToAdd = weekdayNumber;
    if (weekdayNumber <= today.getDay()) {
        daysToAdd = daysToAdd + 7;
    }

    return addDays(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.

Ender
  • 14,995
  • 8
  • 36
  • 51
2

Here is a function to return the next day number.

function nextDay(dayNb){
 return function( date ){
   return new Date(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( new Date() ));
Mic
  • 24,812
  • 9
  • 57
  • 70
1

I recommend to use moment.js if working with dates.

var nextmonday = moment().day(8).format('YYYY-MM-DD'); // e.g. 2015-10-26
var nexttuesday = moment().day(9).format('YYYY-MM-DD'); // e.g. 2015-10-27
var nextwednesday = moment().day(10).format('YYYY-MM-DD'); // e.g. 2015-10-28
var nextthursday = moment().day(11).format('YYYY-MM-DD'); // e.g. 2015-10-29

You can pick different formats and do even more nice stuff, check out: http://momentjs.com/

Avatar
  • 14,622
  • 9
  • 119
  • 198
0

simple calculation:

//for next sunday, set 0, for saturday 6; wednesday == 3;
var needDay = 3;
var fromDate = new Date(); //or any date you calculate from
fromDate.setDate(fromDate.getDate() + (7 - fromDate.getDay()) + needDay);

console.log(fromDate);

+ (7 - fromDate.getDay()): adds to Date amount of days to change the date to sunday.
+ needDay: adds your day you need, if wednesday, just +3;

ya_dimon
  • 3,483
  • 3
  • 31
  • 42