언어 설정

Menu
Sites
Language
How to get day/month/year from input date type

Hello,

it looks an easy question but I am using an input tag with type="date" like that:

<form>
        	<label>Birth date:</label><input type="date" id="tfdate"><br>
    		<label>Email:</label><input type="email" id="tfmail"><br>
    		<label>Login:</label><input type="text" id="tflogin"><br>
    		<label>Password:</label><input type="password" id="tfpwd"><br>
    		<button onclick="login();">Enter</button>
    	</form>

 

and this is my login() function:

function login(){
    		
			sessionStorage.setItem("nomp", document.getElementById("tfnom").value);
			alert(document.getElementById("tfdate").value);
			window.open("page2.html");
			
		}

 

it works well, and its displays (eg: 2015-02-02), but I would like to extract the day, month and year, so what should I do? I've tested the following sentence and it didn't work:

alert(document.getElementById("tfdate").value).getMonth());

Responses

6 댓글
Marco Buettner

You have to convert your value to a date object

var inputDate = document.querySelector('#tfdate),
    date = new Date(inputDate);

alert(date.getMonth());

 

Seoghyun Kang

Hello,

 

Please refer the following code. It works well on the emulator.

 

var input = document.getElementById( 'tfdate' ).value;
var d = new Date( input );

if ( !!d.valueOf() ) {
    year = d.getFullYear();
    month = d.getMonth()+1;
    day = d.getDate();

    // TODO
} 
else { 
    // TODO 
}

 

Palitsyna

Hello,

more information about javascript Date object can be foud here: http://www.w3schools.com/jsref/jsref_obj_date.asp

AVSukhov

Hello,

you need use js Date interface.

or you can use some third-party library, f.e. moment.js

Vikram

Hi,

getMonth() is method for JavaScript and it return the number for month. The return value is an integer between 0 to 11, so please pay attention when you want get the real month date should be using getMonth()+1