Advertisement
Advertisement


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


Question

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?

2016/03/07
1
320
3/7/2016 1:44:39 PM

Accepted Answer

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

    document.querySelector('.date').textContent = output;
2020/03/02
600
3/2/2020 8:56:28 AM


<input type="hidden" id="date"/>
<script>document.getElementById("date").value = new Date().toJSON().slice(0,10)</script>
2013/09/29

To get current date/time in javascript:

var date = new Date();

If you need milliseconds for easy server-side interpretation use

var value = date.getTime();

For formatting dates into a user readable string see this

Then just write to hidden field:

document.getElementById("DATE").value = value;
2017/05/23

By using the value attribute:

var today = new Date();
document.getElementById('DATE').value += today;
2012/09/13

Use the DOM's getElementByid method:

document.getElementById("DATE").value = "your date";

A date can be made with the Date class:

d = new Date();

(Protip: install a javascript console such as in Chrome or Firefox' Firebug extension. It enables you to play with the DOM and Javascript)

2012/09/13

You edit an element's value by editing it's .value property.

document.getElementById('DATE').value = 'New Value';
2012/09/13