【问题标题】:How to calculate booking price depending on dates如何根据日期计算预订价格
【发布时间】:2021-05-02 21:40:52
【问题描述】:

如果此范围内没有日期,如何在下面的代码中添加条件,它为 costRate 分配一个固定值?


        function getPrices(allSeasons, checkin, checkout) {
            const day = 1000*60*60*24;
            return allSeasons.reduce( (totalPrice, season) => {
                let daysInSeason = Math.round(
                    (Math.min(+season.endDate+day, checkout) 
                    - Math.max(season.startDate, checkin)) / day);
                return totalPrice + (daysInSeason > 0 && daysInSeason * season.costRate);
            }, 0);
        } 

        const allSeasons = [
                {startDate: new Date(2017, 1-1, 1), endDate: new Date(2017, 4-1,30), costRate: 300},
                {startDate: new Date(2017, 5-1, 1), endDate: new Date(2017, 9-1,30), costRate: 400},
                {startDate: new Date(2017,10-1, 1), endDate: new Date(2017,12-1,31), costRate: 500}
            ],
            checkin = new Date(2017, 9-1,30),
            checkout = new Date(checkin.getTime() + (48 * 60 * 60 * 1000)),
            totalPrice = getPrices(allSeasons, checkin, checkout);

        console.log(totalPrice);



【问题讨论】:

  • 一天中并不总是有 24 小时可以观察到夏令时,因此 day = 1000*60*60*24 并不总是正确的,因此您需要处理它。 This answer 会有所帮助。

标签: javascript date math calendar reduce


【解决方案1】:

我很确定您可以将daysInSeason * season.costRate 替换为daysInSeason * (season.costRate || VALUE)。如果season.costRate 不存在,它将替换为VALUE

RobG 提出了一个很好的观点,我认为我的回答是不正确的。你想用totalPrice + (daysInSeason>0? daysInSeason*season.costRate : fixedValue)替换它

【讨论】:

  • OP 说“如果此范围内没有日期”,我认为这意味着如果 daysInSeason 为零,那么它应该是喜欢totalPrice + (daysInSeason>0? daysInSeason*season.costRate : fixedValue)。使用 > 可以防止负值并将值强制为 Number。
  • 罗布格!!此解决方案有效,但问题是如果日期范围介于 costRate 和固定值之间,则不会计算平均值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
相关资源
最近更新 更多