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

Looking to make input=date accept DD/MM/YYYY format in Javascript

I am relatively new to Javascript and I have been asked to create a date calculator which will work out what age you are in comparison to the date 31st March 2019 I have got that part working but the client has requested that they be able to fill in the date as DD/MM/YYYY rather than the default MM/DD/YYYY!?

I have tried using a Bootstrap date picker and changing to a text input but I keep getting an invalid date !?

This feels like it should be a line of code that I am missing but a few of the examples I have tried have not worked for me.... so here is my JS and HTML that I am using for it at the moment if anyone can help with this it would be much appreciated!

Codepen : https://codepen.io/raindahl/pen/vzBXgV

1 Answer

Steven Parker
Steven Parker
229,644 Points

If you use a picker, it will constrain the format; and if you use text input, you loose the nice calendar picker.

But if you use Bootstrap, there's a setting where you can define the date format, but you need to know which one to use as you set it up. Otherwise, you may need to parse the date yourself rather than pass the string directly to Date().

And finally, there's a tricky conceptual issue. If you allow either format, how would you tell the difference between Feb 10th and Oct 2nd, for example?

Thanks for this I ended figuring it out by changing the input to text and using a split to allow the date of birth in dd/mm/yyyy

            var birthDate = new Date(birthDate1.split('/')[2], birthDate1.split('/')[1] - 1, birthDate1.split('/')[0]);
          ```
Steven Parker
Steven Parker
229,644 Points

Good self-parsing. You can make it a bit more DRY by doing the split only once:

            var splitDate = birthDate1.split('/');
            var birthDate = new Date(splitDate[2], splitDate[1] - 1, splitDate[0]);