我正在建立一个预订系统,我必须根据旺季/淡季等增加或减少价格。
这是Alessandro的一些好帮助后的最终功能:) 它现在无需在赛季阵列中使用一年。
var seasonArray = [
{
"season": "HIGH Season",
"from": 101,
"to": 315,
"pct": 30
},
{
"season" : "MIDDLE Season",
"from": 316,
"to": 615,
"pct" : 10
},
{
"season" : "LOW Season",
"from": 616,
"to": 915,
"pct" : -10
}
]
var checkin = Date.parse('2017-01-01 00:00:00')
var checkout = Date.parse('2017-09-05 00:00:00')
calcPrice(checkin, checkout);
function calcPrice(checkin, checkout){
var nights = daysBetween(new Date(checkin), new Date(checkout))
var totPrice = calcPeriod(nights,checkin);
var avgPrice = Math.round(totPrice/nights);
totPrice = avgPrice * nights //compensate for math.round difference
var finalPrice = 0;
for (var d = new Date(checkin); d <= checkout; d.setDate(d.getDate() + 1)) {
dn = Number((d.getMonth()+1) + ('0' + d.getDate()).slice(-2))
var season = seasonArray.find(item => {
return item.from <= dn && item.to >= dn
});
var pct = season ? season.pct : 0;
finalPrice += avgPrice * (1 + pct / 100);
}
finalPrice = Math.round(finalPrice)
console.log('totPrice: ' + totPrice)
console.log('finalPrice: ' + finalPrice)
}
答案 0 :(得分:1)
您可以使用以下方法:
find
功能来获得正确的&#34;赛季&#34;用于调整最终价格请参阅我的示例(可以改进):
var seasonArray = [{
"season": "HIGH Season",
"from": Date.parse('2017-01-01 00:00:00'),
"to": Date.parse('2017-03-15 23:59:59'),
"pct": 30
}, {
"season": "MIDDLE Season",
"from": Date.parse('2017-03-16 00:00:00'),
"to": Date.parse('2017-06-15 23:59:59'),
"pct": 10
}, {
"season": "LOW Season",
"from": Date.parse('2017-06-16 00:00:00'),
"to": Date.parse('2017-09-15 23:59:59'),
"pct": -10
}]
var checkin = Date.parse('2017-01-06 00:00:00');
var checkout = Date.parse('2017-05-18 00:00:00');
var days = (checkout / 1000 - checkin / 1000) / 86400; //seconds per day
var totPrice = 13200;
var avgPrice = totPrice / days;
var finalPrice = 0;
for (var d = new Date(checkin); d <= checkout; d.setDate(d.getDate() + 1)) {
var season = seasonArray.find(item => {
return item.from <= d && item.to >= d
});
var pct = season ? season.pct : 0;
finalPrice += avgPrice * (1 + pct / 100);
}
console.log("Final price is: " + finalPrice);
&#13;
我希望它可以帮助你,再见
编辑:我在可能的npe上添加了一些检查
var pct = season? season.pct:0;