首页 > 解决方案 > Javascript 显示下一个可能的交货日期

问题描述

我有一个网站,客户可以在其中看到交货日期。
在此处输入图像描述

这是代码

function getProductRecordHTML(Product, index, quantity, ProductType, blok)
{
    var manufacturer = "", article_show = "", name = "";
                
    var time_to_exe = Product.time_to_exe;

    var displayDate;
    if(time_to_exe == 6)
    {
        const date = new Date();
        date.setDate(date.getDate() + parseInt(time_to_exe));
        displayDate = date.toLocaleDateString();
    }
    if (displayDate) {
  time_to_exe = displayDate;
      
    } else {
      time_to_exe = time_to_exe + "d";
    }

现在,time_to_exe以天为单位给出交货时间 此代码仅通过将这 6 天添加到当前日期来计算下一个交货日期。

我的主要目标是获取周一至周三下午 12 点的时间段,如果为真则time_to_exe显示下周一的日期(例如 23/08/2021),但如果为假(例如从周三下午 12 点之后的时间段)直到周日晚上 11:59)然后time_to_exe显示 1 周后的周一日期(例如 2021 年 8 月 30 日)。

我希望解释清楚。
已经非常感谢用户@Christopher 之前提供的帮助。

标签: javascript

解决方案


Javascript Date对象包含一个getDay()返回星期几的数值的方法。由此可以计算出前一个星期一的日期,然后根据原始日期添加 7 或 14。

此函数接受一个 JavaScriptDate对象并将相关的 Monday 作为另一个返回Date

请注意,setDate()如果设置的日期在当前月份之外,则将酌情更新月份和年份。

        function getMonday(orderDate) {
            orderDate = orderDate || new Date();
            if (!(orderDate instanceof Date)) {
                throw "Invalid date";
            }
            // Get the date last Monday
            let lastMonday = new Date(orderDate);
            lastMonday.setDate(lastMonday.getDate()-lastMonday.getDay()+1);
            // If order date is before Wednesday noon, deliver next Monday. Add 7 to last Monday date
            if (orderDate.getDay()<3 || ((orderDate.getDay() === 3) && orderDate.getHours()<12)) {
                lastMonday.setDate(lastMonday.getDate()+7);
            } else {
                // Otherwise. add 14 to last Monday date.
                lastMonday.setDate(lastMonday.getDate()+14);
            }
            return lastMonday;

        }

输入:

    let testDates = [
      new Date(),
      new Date(2021,7,18,11),
      new Date(2021,7,18,13), 
      new Date(2021,9,1,11), 
      'bad date'
    ];

输出:

Wed Aug 18 2021 10:14:41 GMT+1200 (New Zealand Standard Time), Mon Aug 23 2021 10:14:41 GMT+1200 (New Zealand Standard Time)
Wed Aug 18 2021 11:00:00 GMT+1200 (New Zealand Standard Time), Mon Aug 23 2021 11:00:00 GMT+1200 (New Zealand Standard Time)
Wed Aug 18 2021 13:00:00 GMT+1200 (New Zealand Standard Time), Mon Aug 30 2021 13:00:00 GMT+1200 (New Zealand Standard Time)
Fri Oct 01 2021 11:00:00 GMT+1300 (New Zealand Daylight Time), Mon Oct 11 2021 11:00:00 GMT+1300 (New Zealand Daylight Time)
Invalid Date

演示:https ://jsfiddle.net/dzsf34ga/


推荐阅读