我目前需要在订单收据通知上显示一条消息,让他们知道如果他们在星期一早上7点之前下订单,它将在同一周的星期四发货,如果他们在星期一上午7点之后下订单,交货将在下周的星期四进行。
不幸的是,我不是一个javascript开发人员,但这是我到目前为止所得到的:
<p id="shipment_note"></p>
<script>
var today, cutDate, text;
today = new Date();
cutDate = new Date();
cutDate.getDay([1])
cutDate.setHours([0,1,2,3,4,5,6,7])
if (today.getDay() <= cutDate) {
text = "Your order will ship next Thursday" ;
} else {
text = "Your order will ship Thursday of next week.";
}
document.getElementById("shipment_note").innerHTML = text;
</script>
我不确定这种方法是否正确,并希望在可能的情况下获得一些反馈。
答案 0 :(得分:2)
它说,如果它是星期天,或者它是在7点之前的星期一....
const isBeforeMondayAt7 = d=>d.getDay() === 0 ||
(d=>d.getDay() === 1 && d.getHours() < 7);
if(isBeforeMondayAt7(new Date)){
alert("Your stuff's comin this thursady");
}else{
alert("Your stuff's comin next thurzday");
}
答案 1 :(得分:1)
代码存在许多问题:
var today, cutDate, text;
today = new Date();
cutDate = new Date();
可以
var today = new Date(),
cutDate = new Date(),
text;
然后:
cutDate.getDay([1])
什么都不做。 getDay 不接受任何参数,它返回一周中的日期编号(0 =星期日,1 =星期一等)。不存储或使用返回的值,因此可以删除此行。
cutDate.setHours([0,1,2,3,4,5,6,7])
setHours需要整数参数,而不是数组。传递为值:
cutDate.setHours(0, 1, 2, 3, 4, 5, 6, 7)
将日期时间设置为0:01:02.003。其余值将被忽略。
if (today.getDay() <= cutDate) {
在这里,您要将日期编号与Date对象进行比较。 <=
运算符强制其参数为number,因此 cutDate 将是Date的时间值,对于1970-01之后的任何日期,它总是大于today.getDay()
- 01T00:00:00.006
您想要检查的是:
如果是,请将交货日期设置为星期四。如果没有,请设置下周的星期四的交货日期。我假设你的一周从周一而不是周日开始。
所以在那种情况下:
var today = new Date(),
cutDate = new Date(+today),
opts = {weekday:'long', day:'numeric', month:'long'},
text;
// If it's Monday and before 7am
if (today.getDay() == 1 && today.getHours() < 7) {
// Set cutDate to Thursday
cutDate.setDate(cutDate.getDate() + 3);
text = 'Your order will ship on ' +
cutDate.toLocaleString(undefined, opts) ;
} else {
// Set cutDate to thursday of next week
cutDate.setDate(cutDate.getDate() + (11 - (cutDate.getDay() || 7)));
text = 'Your order will ship on ' +
cutDate.toLocaleString(undefined, opts) ;
}
console.log('Today is ' + today.toLocaleString(undefined, opts) + '. ' + text);
我已经包含了一条更有用的信息(无论如何)。 ; - )
答案 2 :(得分:0)
看来你可能颠倒了if语句中运算符的顺序。
...也许
更改此行...
if (today.getDay() <= cutDate) {
以... 强>
if (today.getDay() =< cutDate) {
答案 3 :(得分:0)
以下是使用三元运算符的示例:
var today = new Date();
var text = new String();
text = (today.getDay() == 0 || (today.getDay() == 1 && today.getHours() < 7) || today.getDay() > 3) ? "Your order will ship next Thursday" : "Your order will ship Thursday of next week";
alert(text);
答案 4 :(得分:0)
这个家伙怎么样?
<script>
var today, cutDate, text;
today = new Date();
cutDate = new Date();
cutDate.getDay([1,2,3,4,])
cutDate.setHours([0,1,2,3,4,5,6,7])
if (today.getDay() >= cutDate) {
text = "Your order will ship Thursday of next week." ;
} else if (today.getDay([5,6,7,0])) {
text = "Your order will ship next Thursday";
}
document.getElementById("shipment_note").innerHTML = text;
</script>