Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

jquery - Get date of specific day of the week in JavaScript

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...