admin管理员组文章数量:1406937
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
3 Answers
Reset to default 4That'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.
本文标签: javascriptJquery Dateparse is returning NaNStack Overflow
版权声明:本文标题:javascript - Jquery Date.parse is returning NaN - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744335861a2601186.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论