javascript - 如何将“Sun, Oct 3”之类的日期字符串与当前日期进行比较?
问题描述
一旦日期使用追加传递字符串中的日期,我将尝试删除给定元素。我需要先转换它吗?
上面的日期字符串列在h2
标签中。
到目前为止,我刚刚这样做是为了访问日期:
var today = new Date();
let dates = document.getElementsByTagName("h2");
for(date of dates){
console.log(date.innerHTML)
}
解决方案
您可以尝试以下方法:
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id); mobile = /Mobi/i.test(nav.userAgent);
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = (node, className)=>{
return node.classList.contains(className);
}
aC = (node, ...classNames)=>{
node.classList.add(...classNames);
return aC;
}
rC = (node, ...classNames)=>{
node.classList.remove(...classNames);
return rC;
}
tC = (node, className)=>{
node.classList.toggle(className);
return tC;
}
// tiny library above for reuse on other loads - magic below can be put on another page except `}) // end load` line
let h2s = Q('h2'), dt = new Date, nd, yr;
dt.setHours(0); dt.setMinutes(0); dt.setSeconds(0); dt.setMilliseconds(0);
yr = dt.getFullYear(); dt = dt.getTime();
for(let h2 of h2s){
nd = new Date(h2.textContent.split(', ')[1]+', '+yr); nd.setHours(0);
nd.setMinutes(0); nd.setSeconds(0); nd.setMilliseconds(0);
if(nd.getTime() < dt)h2.remove();
}
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title><h2> Date Question</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<h2>Mon, Sep 27</h2>
<h2>Tue, Sep 28</h2>
<h2>Wed, Sep 29</h2>
<h2>Thu, Sep 30</h2>
<h2>Fri, Oct 1</h2>
<h2>Sat, Oct 2</h2>
<h2>Sun, Oct 3</h2>
</body>
</html>
推荐阅读
- javascript - ReactJS onClick 不适用于菜单中的第一个元素
- python - 如何在 .txt 文件中打印名称而不重复名称?
- python - 如何旋转特定的刻度标签
- chef-infra - Chef for Windows:修改节点运行列表的脚本
- java - android.os.AsyncTask 中的默认构造函数已弃用
- php - 我如何使用 Laravel 显示我喜欢的所有用户
- opencascade - opencascade BRepOffsetAPI_Sewing 很慢
- c++ - Qt 5.15 更新 QLineEdit styleSheet 触发器...堆栈溢出
- confusion-matrix - 如何从混淆矩阵中得到真阳性、真阴性、假阳性和假阴性
- jquery - jQuery Collision 插件不适用于克隆助手