我想在shopify描述产品中将日期注入html
它会说
我们将从今天开始发货+ 11天.....
如果它下降到星期六或星期日,它将被移动到星期一,因为我们在星期六或星期日休息
代码现在是这样,但不知道如何在必要时将它移动到第一个星期一
// get the destination within the DOM
var wrapper = document.getElementById('productEta'),
// get today as a js Date object
today = new Date(),
// get the Unix of today (miliseconds) and add desired time (3 weeks)
etaUnix = today.getTime() + (60 * 60 * 24 * 11 * 1000),
// convert the new time to date object and then to a human readable string
etaForHumans = new Date(etaUnix).toDateString();
// set the destination inner html to be what it already is
// plus a space and the human readable string.
wrapper.innerHTML += ' ' + etaForHumans;
<div id="productEta">Product will arrive by: </div>
但是脚本也有问题
这实际上并不太难。 Date对象提供了一个函数getDay(),它返回星期几。它是0到6之间的整数。
你可以这样做:
var days = 4;
etaUnix = new Date(today.getTime() + (60 * 60 * 24 * days * 1000));
console.log(etaUnix.getDay())
switch (etaUnix.getDay()) {
case 0:
//sunday
days++;
break;
case 6:
//saturday
days += 2;
break;
}
etaUnix = new Date(today.getTime() + (60 * 60 * 24 * days * 1000));
// convert the new time to date object and then to a human readable string
etaForHumans = new Date(etaUnix).toDateString();
在处理星期六和星期日的交换区中,只需添加一到两天的日期。
顺便说一下 - 你的代码中有一些拼写错误。需要有一个;在声明的最后不是,
// get the destination within the DOM
var wrapper = document.getElementById('productEta'),
// get today as a js Date object
today = new Date(),
// get the Unix of today (miliseconds) and add desired time (3 weeks)
etaUnix = today.getTime() + (60 * 60 * 24 * 11 * 1000),
// convert the new time to date object and then to a human readable string
etaForHumans = new Date(etaUnix);
var day = etaForHumans.getDay()
if(day==0)
etaForHumans.setDate(etaForHumans.getDate() + 1);
if(day==6)
etaForHumans.setDate(etaForHumans.getDate() + 2);
// set the destination inner html to be what it already is
// plus a space and the human readable string.
wrapper.innerHTML += ' ' + etaForHumans+ ' ' + day;
<div id="productEta">Product will arrive by: </div>
var wrapper = document.getElementById('productEta');
var today = new Date(Date.parse('2019-03-05'));
var etaDate = new Date(today.getTime() + (60 * 60 * 24 * 11 * 1000))
while(etaDate.getDay() == 0 || etaDate.getDay() == 6){
//Add one day until it is not saturday or sunday
etaDate.setTime(etaDate.getTime() + (60 * 60 * 24 * 1000));
}
var etaForHumans = etaDate.toDateString();
// set the destination inner html to be what it already is
// plus a space and the human readable string.
wrapper.innerHTML += ' ' + etaForHumans;
<div id="productEta">Product will arrive by: </div>
momentJS。看看这个。允许您以理智的方式玩日期。有插件用于请求nextBusinessDay()等等。
除非你是一个ace Javascript编码器,否则不要乱用日期和香草Javascript。它很糟糕,而且有很多理由存在。少吸吮。