实测JavaScript判断日期有效性的方法

编写一个示例代码来确定javascript中日期的有效性。

判断日期的有效性

判断是否为日期类型,判断方法可以配合“new Date()”使用。

function check(date){ return !Number.isNaN(new Date(date).getDate()) };

console.log( check('2022-12-31') );
// true

console.log( check('2022/12/31') );
// true

console.log( check('2022.12.31') );
// true

console.log( check('2022 12 31') );
// true

console.log( check('2022-12-31 12:34:56') );
// true

console.log( check('a') );
// false

console.log( check('2022-12-32') );
// false

console.log( check('2022_12_31') );
// false

Date.parse()方法

也可以使用“Date.parse”来判断,并返回 1970/1/1 午夜距离该日期时间的毫秒数。

function check(date){ return !Number.isNaN(Date.parse(date)) };

console.log( check('2022-12-31') );
// true

console.log( check('2022/12/31') );
// true

console.log( check('2022.12.31') );
// true

console.log( check('2022 12 31') );
// true

console.log( check('2022-12-31 12:34:56') );
// true

console.log( check('a') );
// false

console.log( check('2022-12-32') );
// false

console.log( check('2022_12_31') );
// false

实测JavaScript判断日期有效性的方法  第1张

示例代码

下面是一个示例代码,点击“判断”按钮判断从表单中获取的日期是否有效的。

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>javascript判断日期有效性的方法</title>
</head>
<body>
	<div style="margin-top:200px;text-align: center;">
		<h2><span class="badge badge-info">结果</span></h2>
		<form>
			<div class="form-group">        
				<input type="text" id="setData">
			</div>
		</form>
		<br>
		<button type="button" onclick="isDate()" class="btn btn-info mt-1">
			判断
		</button>
	</div>

  <script>    

    const isDate = () => {

      let obj = document.getElementsByClassName("badge")[0];

      (!Number.isNaN(new Date(setData.value).getDate())) ? obj.textContent = '是日期' : obj.textContent = '不是日期';

    }

  </script>
</body>

</html>

执行结果

实测JavaScript判断日期有效性的方法  第2张

本文来源:词雅网

本文地址:https://www.ciyawang.com/javascript-date-parse.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐