HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Find next occurring Friday (or any dayOfWeek)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
anyoccurringnextfridayfinddayofweek

Problem

Given a particular Date, want to find the next occurring Friday. I solved it using the below code. Various tested scenarios work good for me.

  • Are there any boundary conditions the code might break?



  • Can it be written any better?



function dates() {
    var dayOfWeek = 5;//friday
    var date = new Date(2013, 10, 13);
    var diff = date.getDay() - dayOfWeek;
    if (diff > 0) {
        date.setDate(date.getDate() + 6);
    }
    else if (diff < 0) {
        date.setDate(date.getDate() + ((-1) * diff))
    }
    console.log(date);
}

Solution

Since you say "Given a particular Date" and "next occurring Friday (or any dayOfWeek)" I think both should be parameters to your function. As it is written, it will only return November 15 always.

function dates(date, dayOfWeek)


But then you should check that dayOfWeek is in range (0-6, thanks SridharVenkat) and probably that date is a valid Date object.

If you do this, you also have to consider not modifying the date parameter and copy it instead.

The names on the variables are clear enough, but not of the function, dates is too broad. getNextDayOfWeek says a lot about what this function does.

function getNextDayOfWeek(date, dayOfWeek)


The logic is correct, I think, I only tested it with a few numbers. But you instead of + ((-1) * diff)) you could simply do - diff.

Finally, you're always outputting the result to the console. If this is more than an exercise, you should return the result, and let the user of the function do with it whatever he/she needs.

Edit: As SridharVenkat said, the range should be 0-6 not 1-7.

Also, using modulo like AlexAtNet suggested you can reduce the code with
resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7)

My (edited) proposal:

function getNextDayOfWeek(date, dayOfWeek) {
    // Code to check that date and dayOfWeek are valid left as an exercise ;)

    var resultDate = new Date(date.getTime());

    resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);

    return resultDate;
}


PS: Please correct me if I said something wrong of if there's more to improve.

Code Snippets

function dates(date, dayOfWeek)
function getNextDayOfWeek(date, dayOfWeek)
function getNextDayOfWeek(date, dayOfWeek) {
    // Code to check that date and dayOfWeek are valid left as an exercise ;)

    var resultDate = new Date(date.getTime());

    resultDate.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7);

    return resultDate;
}

Context

StackExchange Code Review Q#33527, answer score: 24

Revisions (0)

No revisions yet.