I am trying to get today's date using Javscript, which I can do using new Date()
but i would like to know, how can I get it formatted in dd/mm/yyyy and show it in datepicker input?
You can create a function to get Current date formatted in javascript as below
function GetTodaysdate()
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
return dd + '/' + mm + '/' + yyyy;
}
document.getElementById("DateValue").value= GetTodaysdate();
HTML
<input type="text" id="DateValue" />
Output:
OR
Simply use .toJSON.ToSlice
<input type="text" id="CurrentDate"/>
<script>document.getElementById("CurrentDate").value = new Date().toJSON().slice(0,10).split('-').reverse().join('/')</script>
OR
You can use moment.js also
// set current value in textbox with id CurrentDate, using moment.js
$("#CurrentDate").val( moment().format('MMM D, YYYY') );
Any of the above method is good, second method looks quick and easy.
Simply try this to get formatted date in JS
<input type="text" id="date"/>
<input type="text" id="date2"/>
<input type="text" id="date3"/>
<script>
document.getElementById("date").value = new Date().toJSON().slice(0,10); // yyyy-mm-dd format
document.getElementById("date2").value = new Date().toJSON().slice(0,10).split('-').reverse().join('/'); // dd/mm/yyyy format
document.getElementById("date3").value = new Date().toJSON().slice(0,10).replace(/-/g,'/'); //ISO format yyyy/mm/date
</script>
Here is the fiddle to check output https://jsfiddle.net/cx4rqm2h/
Thanks
Try using moment.js, download it or use CDN to link it in your project and use the below code
moment().format('MMMM Do YYYY, h:mm:ss a'); // June 24th 2022, 11:42:22 am
moment().format('dddd'); // Friday
moment().format("MMM Do YY"); // Jun 24th 22
moment().format('YYYY [escaped] YYYY'); // 2022 escaped 2022
moment().format(); // 2022-06-24T11:42:22+05:30
for dd/MM/yyyy format in US local
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
<script>
console.log(moment().format('D/MM/YYYY')); // "24/06/2022"
</script>
That's it.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly