Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Javascript prompt question

Hi,

I am wondering if someone could solve this.

I am trying to compare two dates from the users input and then display the difference in an alert box.

** The code used has to be javascript. **

so it would be something like this:

The user clicks onto a button. The button asks 2 questions. First question asks the user for a date in dd-mm-yy format Another question appears after the input to ask for a second date, same format. The difference is then displayed in an alert box.

Hope someone can find a solution for this

Thank you,

Harry =)

What is the format that you want returned? Number of days from one date to the next?

Yes, its to work out the difference between two dates.

e.g 01/08/2012 compared to 01/11/2015

would return 3 years and 3 months.

1 Answer

Something like this should work and get you most of the way there.

var d1 = new Date(prompt('Enter Start Date (yyyy-mm-dd)'))
var d2 = new Date(prompt('Enter End Date (yyyy-mm-dd)'))

var timeDiff = Math.abs(d2.getTime() - d1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 

alert('There are ' + diffDays + ' between ' + d1 + ' and ' + d2);

Hi Dan,

Thank you that was what i was looking for, works well!

I was having difficulty creating the math for problem.

Thanks again !