How to get current formatted date dd/mm/yyyy in Javascript and append it to an input
To get today's date in dd/mm/yyyy
format and set into an input, follow the code below:
Just modify the query inside .querySelector
to match your input's selector. The above code snippet uses map
to format single digits with leading zeros.
Ensuring consistent date format during form submissions
Consistency is crucial when dealing with date formatting. For your input field to always receive current date in the specified format dd/mm/yyyy
upon each form submission, you can implement the following approach:
Dealing with single-digit days and months
We've seen how map
can be utilized to format single-digit dates. Now let's explore alternative approaches:
Using available libraries judiciously
Libraries such as Moment.js can be handy for dealing with dates, but they can also add unnecessary overhead to your project. Utilize them wisely, only when necessary.
Additional techniques to maneuver the Date object
The key to becoming a proficient coder is having the ability to adapt your solution based on a variety of scenarios. Let's explore some more techniques:
Using toLocaleDateString
This method allows you to format the date according to specific locale and options:
Quick date formatting
If you're a fan of concise code and your environment supports ES5 or higher, here's another way to get your date formatted in dd/mm/yyyy
:
Beware of compatibility issues with older browsers.
Integration with jQuery and moment.js
If you're using jQuery and moment.js, date formatting can be as simple as:
Remember to include both jQuery and moment.js in your project.
Was this article helpful?