2

I have some code that I modified from a site which returns a date like this:

Mon Feb 20 2017 10:40:00 GMT+0000 (Hora padrão de GMT)

What I'm trying to achieve is to make it look like:

10:40

20-02-2017

Here's what I got:

<button onclick="document.getElementById('time').innerHTML=Date()">Click me to display Date and Time.</button>

<p id="time"></p>

I have tried with Date(hh:mm) and Date(dd-mm-yyyy) but it didn't worked.

Community
  • 1
  • 1
newbie
  • 29
  • 1

2 Answers2

0

You should use .getDate(),.getMonth(),.getFullYear(),.getHours(),.getMinutes() methods in order to get date details.

function myFunction(){
    var date=new Date();
    document.getElementById('time').innerHTML=(date.getDate()+'-'+(date.getMonth()+1)+'-'+date.getFullYear()+'<br>'+date.getHours()+':'+date.getMinutes());
}
<button onclick="myFunction()">Click me to display Date and Time.</button>

<p id="time"></p>
Sirko
  • 72,589
  • 19
  • 149
  • 183
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

You can use JavaScript Date Object methods:

document.getElementById('button').onclick = function() {
  var d = new Date(),
      hours = ('0' + (d.getHours())).slice(-2),
      minutes = ('0' + (d.getMinutes())).slice(-2),
      day = ('0' + (d.getDate())).slice(-2),
      month = ('0' + (d.getMonth() + 1)).slice(-2),
      year = d.getFullYear(),
      dateString = hours + '-' + minutes + '<br>' + 
        day + '-' + month + '-' + year;
  
  document.getElementById('time').innerHTML = dateString;
};
<button id="button">Click me to display Date and Time.</button>

<p id="time"></p>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46