1

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.

Jas
  • 805
  • 3
  • 12
  • 21
  • Maybe this might help you out: https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone – Vikas Yadav Jan 18 '19 at 13:36

2 Answers2

1

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');
}
Andy
  • 61,948
  • 13
  • 68
  • 95
  • 1
    Excellent, thank you for the refactoring advice and tips. I will implement these and learn from these findings! Thanks one again! @Andy – Jas Jan 18 '19 at 14:18
-1

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
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345