Date Formatting Help JavaScript

Hello,

We have this script running on a landing page, that is pushing a timestamp into a hidden field called ‘Conversion_Time’, it works fine, but the date needs to be formatted like, MM/DD/YYYY HH:MM:SS (01/04/2022 10:10:54).

The date formats incorrectly like this currently, YYYY/MM/DD HH:MM:SS (2022/01/04 10:10:54). Can anyone help? Please note the TIME is fine, the date just needs to have the year at the end.

See the script below. Thanks SO much, I really appreciate any help.

<script>
// Change the word Date_Submitted in the following line to the name of your hidden field label.
// It has to match exact label, including capitals, underscore, etc...
var inpElm = document.getElementById('Conversion_Time');                                     
var d = new Date();
var pD = d;
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);  
window.setTimeout(sD, 5000);
window.setInterval(sD, 30000);
function sD(){
dt = new Date();
inpElm.value = dt.toLocaleDateString().concat(" ", dt.toLocaleTimeString());
inpElm.value = localISOTime.slice(0, 19).replace(/-/g, "/").replace("T", " ");  
}
</script>

This link maybe useful to you

Just having a play, came up with this

function getDate() {

  const options = {
      year: 'numeric', month: '2-digit', day: '2-digit',
      hour: 'numeric', minute: 'numeric', second: 'numeric',
      hour12: false
  }

  return new Intl.DateTimeFormat('en-US', options)
      .format(new Date()) // need to remove comma e.g. 01/04/2022, 16:28:01
      .split(',') // split on comma
      .join('') // join without
}

function updateDate() {
    document.getElementById('Conversion_Time').value = getDate()
}

window.setTimeout(updateDate, 1000)
window.setInterval(updateDate, 2000)

codepen

At the end you should be very sure to use such a date format for any other purpose then showing it to the user. Internally you should always use and store it in an ISO standard

1 Like