Date的Invalid Date

简介: Date的Invalid Date

使用Date()构造日期对象,如果传入非日期格式或者错误的日期格式的字符串,仍然能构造出Date对象。

var date = new Date("dream");
console.log('date:', date);  //Invalid Date
console.log('date:', typeof date);  //“object”
console.log('date:', date instanceof Date);  //true
 
 
var date2 = new Date("2019-053");
console.log('date2:', date2);  //Invalid Date
console.log('date2:', typeof date2);  //“object”
console.log('date2:', date2 instanceof Date);  //true

示例里使用非日期格式"dream"(错误日期格式“2019-053”)构造Date对象

直接输出date,结果为Invalid Date

使用typeof判断date的类型,得到结果为“object”

使用instanceof检测date是否为Date类型,结果为true。

使用Date的getTime()方法,Invalid Date对象返回的是一个NaN,可以利用这点来检查Date对象是否为Invalid Date。

function isValidDate(date) {
  return date instanceof Date && !isNaN(date.getTime())
}
 
// 也可以
//  function isValidDate(date) {
//    return date instanceof Date && !isNaN(date.valueOf())
//  }
 
var date = new Date("dream");
console.log('结果',isValidDate(date)); //false
 
var date2 = new Date("2019-053");
console.log('结果',isValidDate(date2)); //false
 
var date3 = new Date("2019-05-09");
console.log('结果',isValidDate(date3)); //true


目录
相关文章
|
SQL 关系型数据库 MySQL
|
11月前
|
SQL
tp5时间戳字段报错Invalid datetime format: 1292 Incorrect datetime value
tp5时间戳字段报错Invalid datetime format: 1292 Incorrect datetime value
110 0
|
1月前
DATE_FORMAT函数使用
DATE_FORMAT函数使用
186 0
|
7月前
|
关系型数据库 MySQL PostgreSQL
PSQLException: 错误: 函数 date_format(timestamp without time zone, unknown) 不存在
PSQLException: 错误: 函数 date_format(timestamp without time zone, unknown) 不存在
132 0
|
存储 JavaScript 前端开发
new Date(dateString)
new Date(dateString)
89 0
new Date()
new Date()
95 0
resolveType - when is date type for DateFormat used when initialization
Created by Wang, Jerry, last modified on Oct 27, 2015
119 0
resolveType - when is date type for DateFormat used when initialization