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.
You need to specifically add the locale
'en-GB'
totoLocaleString
:With regard to your code, it could do with a little refactoring.
1) Developers rarely use
document.write
for anything any more2) 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.