CeeJay CeeJay - 27 days ago 9
Javascript Question

How to use prompt and Date object together?

I want a user to be able to enter a date for new Date object by using prompt. When I initiate a date like this


var dob = new Date("April 2, 1984");


it works, but if I use prompt it becomes invalid.

var urDate = prompt('Date of birth (Ex.:January 3)');
var urYear = prompt('Date of birth (Ex.:1933)');
var dob = new Date(urDate,urYear);
document.write(dob);


What should I do?

Answer Source

You should concatenate two values urDate and urYear like this:

var urDate = prompt('Date of birth (Ex.:January 3)');
var urYear = prompt('Date of birth (Ex.:1933)');
var dob = new Date(`${urDate} ${urYear}`);