我将如何修复此功能以根据日期更改月份?

我正在尝试创建一个函数,该函数根据字符串中提供的日期创建动态日期范围。


到目前为止我做了什么:


在我要更改的字符串中捕获日期;


检查该日期是否为星期四(如果是,则该范围需要考虑周末)


我需要做什么:


找到一种方法来获取范围内的第二个日期以考虑周末;


想办法确保第二个日期考虑到该月的最后一天。


为旧语法道歉,GTM 不喜欢使用 ES6 的任何东西,所以我在这个项目上有点受限。


注意我使用的是 DD/MM/YYYY


var regex = /[\d\/\d\/\d]/g;

var text = dument.querySelector('.shipmentLineTitle b');

var originalDate = text.innerText.match(regex, "");

if (originalDate.length > 10) {

    originalDate.pop();

    originalDate.join('');

}

var ogDateString = originalDate.join('');

var dayNumber = originalDate.splice(0, 2).join('');

var monthNumber = originalDate.splice(1, 2).join('');

var yearNumber = originalDate.splice(2, 4).join('');


// if originalDate is a thursday (5) dynamicString will need to be a Monday (1).


var date = new Date(yearNumber, monthNumber -1, dayNumber);

var dynamicDateString = "";


if (date.getDay == 5) {

    var newDate = new Date(date) + (86400000 * 3);


    var dd = newDate.getDate();

    var mm = newDate.getMonth() +1;

    var yy = newDate.getFullYear();


    dymamicDateString = dd + '/' + mm + '/' + yy;

} else {

    var newDate = new Date(date) + 86400000;


    var dd = newDate.getDate();

    var mm = newDate.getMonth() +1;

    var yy = newDate.getFullYear();

    dynamicDateString = dd + '/' + mm + '/' + yy;

}


var newContent = 'Delivery will be made between ' + ogDateString + ' - ' + dynamicDateString + '. An accurate delivery date will be provided after you place your order.';


text.innerText = newContent;

<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 09/10/2020 (1 delivery)</b></span>


子衿沉夜
浏览 109回答 2
2回答

元芳怎么了

星期四是第 4 天这是一个更简单的脚本var textField = document.querySelector('.shipmentLineTitle b'),&nbsp; text = textField.innerText,&nbsp; originalDate = text.match(/\d{2}\/\d{2}\/\d{4}/)[0].split("/"),&nbsp; dayNumber = +originalDate[0],&nbsp; monthNumber = +originalDate[1],&nbsp; yearNumber = +originalDate[2],&nbsp; date = new Date(yearNumber, monthNumber - 1, dayNumber, 15, 0, 0, 0),&nbsp; aDay = 86400000,&nbsp; newDate = new Date(date),&nbsp; day = date.getDay(),&nbsp; daysToAdd = 1; // Sunday to Wednesday// if originalDate is a Thursday (4) or Saturday (6), dynamicString will need to be a Monday (1).if (day === 4) daysToAdd = 4; // Thursday - delivery Mondayelse if (day === 6) daysToAdd = 2; // SaturdaynewDate.setDate(newDate.getDate() + daysToAdd);var dd = newDate.getDate(),&nbsp; mm = newDate.getMonth() + 1,&nbsp; yy = newDate.getFullYear(),&nbsp; dynamicDateString = dd + '/' + mm + '/' + yy,&nbsp; newContent = text + ' - ' + dynamicDateString + '</b>. An accurate delivery date will be provided after you place your order.';textField.innerHTML = newContent;<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 08/10/2020 (1 delivery)</b></span>

慕姐4208626

我建议用户 moment.js 一个非常好的日期库来操作日期。它有很多添加/减去日期、小时、天等的功能。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript