Search code examples
javascripthtmlinputtagshidden

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


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?


Solution

  • I hope this is what you want:

    const today = new Date();
    const yyyy = today.getFullYear();
    let mm = today.getMonth() + 1; // Months start at 0!
    let dd = today.getDate();
    
    if (dd < 10) dd = '0' + dd;
    if (mm < 10) mm = '0' + mm;
    
    const formattedToday = dd + '/' + mm + '/' + yyyy;
    
    document.getElementById('DATE').value = formattedToday;
    

    How do I get the current date in JavaScript?