How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

VolosBlur picture VolosBlur · Sep 13, 2012 · Viewed 1.2M times · Source

I would like to add a current date to a hidden HTML tag so that it can be sent to the server:

<input type="hidden" id="DATE" name="DATE" value="WOULD_LIKE_TO_ADD_DATE_HERE">

How can I add a formatted date to the VALUE attribute?

Answer

Aelios picture Aelios · Sep 13, 2012
   const monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"];
    const dateObj = new Date();
    const month = monthNames[dateObj.getMonth()];
    const day = String(dateObj.getDate()).padStart(2, '0');
    const year = dateObj.getFullYear();
    const output = month  + '\n'+ day  + ',' + year;

    document.querySelector('.date').textContent = output;