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">
开发者_如何学Python <!--
// 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?
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>
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.
精彩评论