尝试使用 JavaScript 从 HTML 元素中提取日期并将它们与今天的日期进行比较,如果它们在 30 天内,则更改文本颜色

Trying to pull dates from HTML elements with JavaScript and compare them to today's date and if they are within 30 days change the text color

我对 programming/web 开发完全陌生。

我想做什么: 我正在尝试编写 JavaScript,它将从网页或在线电子表格中获取日期并更改文本或单元格背景的颜色。颜色变化将取决于从 HTML 元素或在线电子表格中获取的日期是否在距今天日期 14 天或 30 天内。

这是我想要处理的 html 个元素的示例。我将日期设置为各种格式以尝试使用它们。

到目前为止我写的Javascript我在这里发帖是因为我可以让元素改变颜色但我不认为改变实际上是基于天数而且我不能比较我想要的天数。

const now = new Date().toDateString();
const date1 = document.getElementById('test1').innerText;

for (let i = 0; i <= test.length; i++) {

  i += test[i];

  if (date1 <= now)
    console.log('safe');
  if (date1 >= now)
    document.getElementsByClassName('test')[0].style.color = 'purple';
};
<div class='test'>
  <p id="test1">February 22 2022</p>
  <br>
  <p id="test">17/2/2022</p>
  <br>
  <p id="test">17 3 2022</p>
  <br>
  <p id="test">17 4 2022</p>
  <br>
</div>

与其将它们转换为字符串,不如直接使用日期对象进行比较,Date 构造函数可以将字符串作为输入并从中生成对象。

尝试这样的事情:

const now = new Date();
const dates = document.getElementsByTagName('p');

for (d of dates) {
  let dateString = d.innerText;
  let dateObj = new Date(dateString);

  if (dateObj < now)
    console.log(`${dateObj} is older`);
  else
    console.log(`${dateObj} is today or newer`);
};
<div class="test">
  <p>February 22 2022</p>
  <br>
  <p>2/22/2022</p>
  <br>
  <p>2021 2 17</p>
  <br>
</div>

编辑:感谢 abt 片段的创意!不太了解该功能。还发现JS不理解DD/MM/YYYY,其中MM是2或02 :(

还根据此处的其他建议和一个希望更易于理解的示例更新了代码。

  1. ID 必须是唯一的。使用 class 或者在我的例子中使用容器中的选择器
  2. 你的测试不是一个数组,它是一个字符串
  3. 您显示的哪些日期有效?我假设在我的代码中 dd/mm/yyyydd mm yyyyMmm(...) dd yyyy

const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
const now = new Date();
document.querySelectorAll('.test p').forEach(p => {
  const dString = p.textContent;
  let [date, month, year] = dString.split(/[ \/]/)

  const textMonth = months.indexOf(date.slice(0, 3))
  if (textMonth != -1) { // we found a month name
    date = month
    month = textMonth
  } else month -= 1;
  const d = new Date(year, month, date)
  console.log(d, d <= now)
  p.classList.toggle("safe", !isNaN(d) && d <= now)
  p.classList.toggle("unknown", isNaN(d))
  p.classList.toggle("unsafe", !isNaN(d) && d > now)
})
.safe {
  color: green;
}

.unsafe {
  color: purple;
}

.unknown {
  color: red;
}
<div class='test'>
  <p>February 22 2022</p>
  <br>
  <p>17/1/2022</p>
  <br>
  <p>17/2/2022</p>
  <br>
  <p>17 3 2022</p>
  <br>
  <p>17 4 2022</p>
  <br>
  <p>17 4 2025</p>
  <br>
</div>

如果您正在使用任何 single-page 应用程序,请安装 moment.js 库(npm I moment)或者如果您正在使用 HTML javascript,请添加 moment.js CDN

下面的代码只是你逻辑问题的一个例子而已

<!DOCTYPE html>
<html>

<head>
    <title>Page Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
    <div id="Reset">
        <button>Check date is under 30 days</button>
    </div>

    <script>
        $(document).ready(function () {
            $("#Reset").click(function () {
                /* $.get("https://jsonplaceholder.typicode.com/todos", function (data) {
                    console.log(data);
                    alert("Load was performed.");
                }) */
                let curretDate = new Date();
                let dateToCheck = new Date("01/12/2022");
                let date_of_30_subtract = moment(curretDate).subtract(30, 'days');
                
                console.log(moment(dateToCheck).isBetween(date_of_30_subtract,curretDate ))
            });
        });
    </script>
</body>

</html>

您可以设置在哪个日期之前检查 14 或 30 天。 Thant 将减去这些天数并得到减去后的日期。