0

Hi I have a javascript code as below. But its not like how i want it to be. I mean how the time and date is presented.

function getDateTime() {
        var now     = new Date(); 
        var year    = now.getFullYear();
        var month   = now.getMonth()+1; 
        var day     = now.getDate();
        var hour    = now.getHours();
        var minute  = now.getMinutes();
        var second  = now.getSeconds(); 
        if(month.toString().length == 1) {
             month = '0'+month;
        }
        if(day.toString().length == 1) {
             day = '0'+day;
        }   
        if(hour.toString().length == 1) {
             hour = '0'+hour;
        }
        if(minute.toString().length == 1) {
             minute = '0'+minute;
        }
        if(second.toString().length == 1) {
             second = '0'+second;
        }   
        var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;   
         return dateTime;
    }

    // example usage: realtime clock
    setInterval(function(){
        currentTime = getDateTime();
        document.getElementById("digital-clock").innerHTML = currentTime;
    }, 1000);
<div id="digital-clock"></div>

The output is like this enter image description here

Instead, I want it to be like this: enter image description here

Also, is it possible if I want to display in language other than English?

  • check out this - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString – ericmp Dec 02 '22 at 13:00
  • Aside: that `.toString().length == 1` check would be much simpler as `< 10`… – deceze Dec 02 '22 at 13:00
  • 1
    Also, this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat – Salketer Dec 02 '22 at 13:01

0 Answers0