如果超过 html 日期 7 天或更长时间并且未付款,则仅使用 vanilla JS 更改 innerHTML

If 7 or more days past html date and if not paid change the innerHTML using only vanilla JS

如果我有以下硬编码 HTML 日期:

<h2 id="date">17/02/2018</h2>
<h2 id="status">Not paid</h2>

截止日期为 h2 日期加上 1 周或更长时间。

我将如何编写 javascript,以便如果截止日期已过并且未支付 h2 状态,那么我将如何更改 <h2 id="status">Not paid</h2> 以显示文本 overdue 而不是Not paid

我尝试获取当前日期,然后使用 moment.js 添加 7 天: moment().format('L').add(7, 'days'); 因为它给了我相同的日期格式 (dd/mm/yyyy) 然后将它与 h2 日期进行比较但问题是因为 moment.js 总是会得到 今天的日期 并向其添加 7 天,以便将来始终为 7 天。不是从 h2 日期算起的 7 天。

一个看似简单的问题,纠结了2天

您需要先访问日期,方法是从日期元素中提取文本:

let myDate = document.getElementById('date').innerText;

然后,您可以使用 moment 将其实例化为时刻日期(假设它的格式有效):

let momentDate = moment(myDate, "DD/MM/YYYY");

现在您可以使用 momentDate 添加天数,将其与其他日期进行比较等,例如:

let oneWeekLater = momentDate.add(7, 'days');

如果你想改变 "status" 元素的值,你可以这样做:

let statusElement = document.getElementById("status");
statusElement.innerText = "Thank you for paying!";

解决方法如下:

const currentStatus = document.getElementById('status').innerText;

let myDate = document.getElementById('date').innerText;
//get the date in the html
// 100% correct

let momentDate = moment(myDate, "DD/MM/YYYY");
// gets the myDate variable and converts it into soemthing JS can understand
// 100% correct

let oneWeekLater = momentDate.add(7, 'days').format("YYYY/MM/DD");
// Need to comapare the dates based on bigest number first which is the year then 
month etc... it then adds one week on to it


let today =  moment(new Date()).format("YYYY/MM/DD");
// prints out todays date in the same format as oneWeekLater so they cna be compared

if(currentStatus.innerText == "Up-paid"){
  if (oneWeekLater >= today){
    document.write('Overdue')
  } else{
    document.write('not paid')
  }
} else {
  currentStatus.innerText = "Thank you for paying"
}