Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  141] [ 3]  / answers: 1 / hits: 30125  / 11 Years ago, fri, october 25, 2013, 12:00:00

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.


More From » html

 Answers
17

Your 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 Dates 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 :)


[#74723] Thursday, October 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
randall

Total Points: 492
Total Questions: 99
Total Answers: 103

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;