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

javascript - Jquery Date.parse is returning NaN - Stack Overflow

programmeradmin8浏览0评论

I'm trying to parse a value from an input type=datetime-local using Jquery. I do know why, but it s returning me a NaN when I tell it to parse a variable.

$("#new-broadcast-arrival-time").on("change", function(){
    var a = $(this).val();
    var d = Date.parse(a);
    console.log(a);
    console.log(d);
})

and my output is

123213-03-12T12:12

NaN

What is wrong ?

2) My expectation output is yyyymmddhhmmss

How can I have this ?

I'm trying to parse a value from an input type=datetime-local using Jquery. I do know why, but it s returning me a NaN when I tell it to parse a variable.

$("#new-broadcast-arrival-time").on("change", function(){
    var a = $(this).val();
    var d = Date.parse(a);
    console.log(a);
    console.log(d);
})

and my output is

123213-03-12T12:12

NaN

What is wrong ?

2) My expectation output is yyyymmddhhmmss

How can I have this ?

Share Improve this question asked May 25, 2016 at 19:55 vbotiovbotio 1,7245 gold badges29 silver badges58 bronze badges 1
  • 5 Date is probably out of range. The year is "123213" – jeffjenx Commented May 25, 2016 at 19:58
Add a ment  | 

3 Answers 3

Reset to default 4

That's probably because 123213-03-12T12:12 is not a valid date format. Date.parse() will return NaN if it does not recognize a date string or if it is an invalid date. In your case, it seems like it is an invalid date format.

Here is an excerpt from the docs:

... NaN if the string is unrecognised or, in some cases, contains illegal date values (e.g. 2015-02-31).

In your case, the given date is invalid.

So to answer your question if you want the output to be: yyyymmddhhmmss

You have to use dateFormat

example code with dateFormat:

var a = $(this).val();
var dateFormat = require('dateformat');
var yourdate = new Date(a);
dateFormat(yourdate, "yyyy mm dd hh:mm:ss");

An other possible way would be to use moment.js which is a plete library that can format dates and do alot of stuff with them. You can take a look at their doc it is fully detailed.

EDIT:

If using a library really bothers you, here is how you could do it without one. (Dirty but works...)

 var str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +  date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

You shouldn't use Date.parse. From MDN:

It is not remended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be acmodated).

In your case it's returning NaN, because it's out of range — the year is 123213.

I remend you using Moment.js library instead.

发布评论

评论列表(0)

  1. 暂无评论