最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if the given string is a date object - Stack Overflow

programmeradmin2浏览0评论

I need to check whether the given string is date object or not.

Initially I used

 Date.parse(val)

If you check Date.parse("07/28/2014 11:23:29 AM"), it'll work.
But if you check Date.parse("hi there 1"), it'll work too, which shouldn't.

So I changed my logic to

val instanceof Date 

But for my above date string, "07/28/2014 11:23:29 AM" instanceof Date it returns false.

So, is there any way with which I can appropriately validate my string against Date?

I need to check whether the given string is date object or not.

Initially I used

 Date.parse(val)

If you check Date.parse("07/28/2014 11:23:29 AM"), it'll work.
But if you check Date.parse("hi there 1"), it'll work too, which shouldn't.

So I changed my logic to

val instanceof Date 

But for my above date string, "07/28/2014 11:23:29 AM" instanceof Date it returns false.

So, is there any way with which I can appropriately validate my string against Date?

Share Improve this question asked Jul 28, 2014 at 6:26 PrashantJPrashantJ 4571 gold badge3 silver badges9 bronze badges 1
  • try to replace date string 07/28/2014 11:23:29 AM to 29-07-2014 11:23:29 AM – Satish Sharma Commented Jul 28, 2014 at 6:30
Add a comment  | 

2 Answers 2

Reset to default 11

You can use Date.parse to check if it is a date or not using below code. Date.parse() return number if valid date otherwise 'NaN' -

var date = Date.parse(val);
if(isNaN(date))
 alert('This is not date');
else
 alert('This is date object');

For more information - Date Parse()

function isDate(val) {
    var d = new Date(val);
    return !isNaN(d.valueOf());
}

Hope helps you

发布评论

评论列表(0)

  1. 暂无评论