问题
I am trying to output something similar to the following on our ecommerce website:
Order by 5pm today for dispatch on Monday
Obviously, the word Monday would be replaced by the name of the next day (ideally the next working day i.e. not Saturday or Sunday).
I have the following simple javascript script that does the most basic version. It simply outputs the current day name:
<p id="orderBy">
<script type="text/javascript">
<!--
// Array of day names
var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday");
var now = new Date();
document.write("Order by 5pm today for dispatch on " + dayNames[now.getDay()]);
// -->
</script>
</p>
Is there a way of manipulating the above code to +1 the day name? So it would output tomorrows name rather than today. Furthermore, is it possible to skip the weekends?
回答1:
Another way...
<p id="orderBy">
<script type="text/javascript">
<!--
// Array of day names
var dayNames = ["Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"];
var nextWorkingDay = [ 1, 2, 3, 4, 5, 1, 1 ];
var now = new Date();
document.write("Order by 5pm today for dispatch on " +
dayNames[nextWorkingDay[now.getDay()]]);
// -->
</script>
</p>
回答2:
Here's a one-liner that will also skip weekends:
document.write("Order by 5pm today for dispatch on " +
dayNames[ ((now.getDay() + 1) % 6 ) || 1 ] );
If getDay is Friday (5), then + 1 is 6, % 6 is 0, which is falsey so || 1 makes it 1 (Monday).
If getDay is Saturday (6), then + 1 is 7, % 6 is 1 (Monday)
If getDay is Sunday (0), then + 1 is 1, % 6 is 1 (Monday)
No need to maintain a parallel Array.
来源:https://stackoverflow.com/questions/4843245/display-tomorrows-name-in-javascript