1

I have the following code which returns time and date, but I want to change the date format from mm/dd/yyyy to dd/mm/yyyy.

Can you change the format of the Date() object below?

<script id="clockScript1" type="text/javascript">
var clockInterval;
$(function () {
    if (clockInterval) return;

    //add logo
    var div1 = $('<div/>');
    var logo = new Image();

    logo.src = '/dashboardlogo.png'
    logo.height = 60;
  div1[0].style.margin = '10px auto';

    div1.append(logo);

    //add clock
    var div2 = $('<div/>');
    var p = $('<p/>');

    div2.append(p);
    div2[0].style.margin = '5px';

    function displayTime() {
        p.text(new Date().toLocaleString());
    }

    clockInterval = setInterval(displayTime, 1000);

    //add to toolbar when it's available
    var addToToolbarTimer;

    function addToToolbar() {
        var toolbar = $('.md-toolbar-tools');

        if(!toolbar.length) return;

        toolbar.append(div1);
        toolbar.append(div2);
        clearInterval(addToToolbarTimer);
    }
    addToToolbarTimer = setInterval(addToToolbar, 100);
});

Liam
  • 27,717
  • 28
  • 128
  • 190
solutery7
  • 21
  • 4
  • If you read the documentation on the function toLocaleString (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) you are using, you can see that you can pass a language code as parameter to the function to change the Date format. – Máté Wiszt Mar 13 '19 at 12:02

3 Answers3

2

Specific to your requirement; you can pass "en-GB" locale string as a first argument to toLocaleDateString.

console.log((new Date()).toLocaleDateString("en-GB"))

Will result into

"13/03/2019"

freedomn-m
  • 27,664
  • 8
  • 35
  • 57
ejaz
  • 333
  • 2
  • 15
1

Store the date then extract the needed parts.

var someDate = new Date();
someDate.getDate() + "/" + (someDate.getMonth() + 1) + "/" + someDate.getFullYear()

Output:

"13/3/2019"
Liam
  • 27,717
  • 28
  • 128
  • 190
0

If you are working with dates, moment.js might be your best friend.

In your case:

moment().format('DD/MM/YYYY');
ZioTino
  • 174
  • 6
  • This might be a useful comment, it's not an answer given the OP hasn't tagged a library or asked for one. – RobG Mar 13 '19 at 21:38