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
221 views
in Technique[技术] by (71.8m points)

make Javascript future date adjust for weekends

I am using the following javascript code to display 7 days into the future based off the current date.

<script >
<!--

var m_names = ["January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December"];

var d_names = ["Sunday","Monday", "Tuesday", "Wednesday", 
"Thursday", "Friday", "Saturday"];

var myDate = new Date();
myDate.setDate(myDate.getDate()+7);
var curr_date = myDate.getDate();
var curr_month = myDate.getMonth();
var curr_day  = myDate.getDay();
document.write(d_names[curr_day] + "," + m_names[curr_month] + " " +curr_date);

//-->
</script>

I am using this javascript code to let my customers know when they will get their packages by.

The script automatically adds 7 days to the current date. I would like it to adjust the future date (+7) if the current date falls on a Saturday or Sunday.

If the current date is a Saturday I would like it to add (+9 days). If the current date is a Sunday I would like it to add (+8 days)

All current days that fall between Monday-Friday I would like it to add (+7 days).

Any thoughts on how this can be achieved?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Following CompuChip's answer (sorry, C, it got too long for a comment!):

if (myDate.getDay() == 5) // Saturday
    myDate.setDate(myDate.getDate()+9);
else
if (myDate.getDay() == 6) // Sunday
    myDate.setDate(myDate.getDate()+8);
else
    myDate.setDate(myDate.getDate()+7);

You could also use a switch statement here (and if you don't know how to: this is a perfect moment to look it up and experiment with it!).

A third interesting way is to use an array. Now you know Monday=0, Tuesday=1, etc., you can build a list of values-to-add for every weekday:

var nextWeek = [7, 7, 7, 7, 7, 9, 8];
myDate.setDate(myDate.getDate()+nextWeek[myDate.getDay()]);

However, there is a strict relation between day-of-week number and the adjust value:

myDate.setDate( myDate.getDate()+ ((myDate.getDay() < 5) ? 7 : 14-myDate.getDay()) );

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

2.1m questions

2.1m answers

60 comments

56.8k users

...