How to format a JavaScript date to UK format?

6.8k views Asked by At

I am currently learning my way around JavaScript and have a question about a function that I have which will generate a real time date and time for use in my application.

I'd like to format my JavaScript date to a specific UK format, as it currently is in US format.

My code currently looks like this

<a> 
        <script type="text/javascript">
            document.write ('<p><span id="date">', new Date().toLocaleString(), '<\/span>.<\/p>')
            if (document.getElementById) onload = function () {
                 setInterval ("document.getElementById ('date').firstChild.data = new Date().toLocaleString()", 50)
                                }
        </script>
    </a>

The above then displays as follows:

1/18/2019, 12:58:13 PM

Expected
UK format is DD/MM/YYYY so hence I want the date to be 18/1/2019. The time is what I expected.

2

There are 2 answers

1
Andy On BEST ANSWER

You need to specifically add the locale 'en-GB' to toLocaleString:

<a>
  <script type="text/javascript">
    document.write('<p><span id="date">', new Date().toLocaleString('en-GB'), '<\/span>.<\/p>')
    if (document.getElementById) onload = function() {
      setInterval("document.getElementById ('date').firstChild.data = new Date().toLocaleString('en-GB')", 1000)
    }
  </script>
</a>

With regard to your code, it could do with a little refactoring.

1) Developers rarely use document.write for anything any more

2) Passing a string to setInterval is considered an anti-pattern as it can be used for XSS attacks.

3) You don't need to update the code every 50th of a second. Once a second will be fine.

Here a refactor which is a little easier to follow.

// Add the HTML to the document body element
document.body.innerHTML = '<p><span id="date"></span><p>';

// Grab the date element
const date = document.querySelector('#date');

// Create a timer that calls the `changeDate` function once a second
const timer = setInterval(changeDate, 1000);

function changeDate() {

  // Set the textContent of `date` to the new date
  date.textContent = new Date().toLocaleString('en-GB');
}

0
Kamil Kiełczewski On

Try

let d= new Date().toLocaleString('en-GB')
let dNoZeros = d.replace(/^0?(\d?\d).0?(\d?\d)/, "$1/$2");

console.log(d);          // 18/01/2019, 14:20:58
console.log(dNoZeros);   // 18/1/2019, 14:20:58