admin管理员组文章数量:1305315
I am using the following for a user to input a date in a form:
<input name="name" type="date" id="id"/>
I am wondering if there is a way to parse the Day, Month, and Year from this and set them into different variables. I am trying to use only Javascript, not PHP.
The 3 variables would be integers.
Thanks.
I am using the following for a user to input a date in a form:
<input name="name" type="date" id="id"/>
I am wondering if there is a way to parse the Day, Month, and Year from this and set them into different variables. I am trying to use only Javascript, not PHP.
The 3 variables would be integers.
Thanks.
Share Improve this question asked Oct 25, 2013 at 18:49 Jake ChasanJake Chasan 6,5609 gold badges48 silver badges93 bronze badges4 Answers
Reset to default 7Your best option, if you're accepting input and converting it to a date, either split by part or as a Date
object, is to simply construct a new Date
object by passing it the input value:
var input = document.getElementById( 'id' ).value;
var d = new Date( input );
if ( !!d.valueOf() ) { // Valid date
year = d.getFullYear();
month = d.getMonth();
day = d.getDate();
} else { /* Invalid date */ }
This way you can leverage Date
s handling of multiple input formats - it will take YYYY/MM/DD, YYYY-MM-DD, MM/DD/YYYY, even full text dates ( 'October 25, 2013' ), etc. without having you write your own parser. Valid dates are then easily checked by !!d.valueOf()
- true if it's good, false if not :)
You will want to split the value on '-', not '/'. E.g.,
$( "input" ).change(function(e) {
var vals = e.target.value.split('-');
var year = vals[0];
var month = vals[1];
var day = vals[2];
console.info(day, month, year);
});
Here is a jsbin of a working example: http://jsbin./ayAjufo/2/edit
You may try like this:-
function parseDate(input) {
var str= input.split('/');
return new Date(str[0], str[1]-1, str[2]);
}
str[1]-1
as months start from 0.
You may also check Date.parse(string) but this implemetation dependent.
Regular expression improvements with ES9. You can use like that.
const
reDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/,
match = reDate.exec('2019-05-29'),
year = match[1], //2019
month = match[2], //05
day = match[3]; //29
本文标签: htmlParse Datemonthand Year from Javascript quotDatequot formStack Overflow
版权声明:本文标题:html - Parse Date, Month, and Year from Javascript "Date" form - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739902496a2207288.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论