0

I am trying to use JavaScript to display the date and time on my webapp.

Although I have had success doing this my date and time is printed as 29/5/13. I want it to have a zero in front of the month if it is less than ten. I have tried using an if statement but didnt have much sucess. My code that I currently have is:

<script language="javascript"> 

    today = new Date(); 
    document.write("<BR>Time: ", today.getHours(),":",today.getMinutes()); 
    document.write("<BR>Date: ", today.getDate(),"/",today.getMonth()+1,"/",today.getYear()-100);


</script>

Any help would be greatly appreciated.

user229044
  • 232,980
  • 40
  • 330
  • 338
Adam.13
  • 41
  • 1
  • 4
  • 12

4 Answers4

4

Live Demo

function pad(num) {
  return ("0"+num).slice(-2);
}

To use:

+  pad(today.getMonth()+1))
animuson
  • 53,861
  • 28
  • 137
  • 147
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

Try this:

var today = new Date();
var month = ((today.getMonth() + 1) < 10) ? '0' + (today.getMonth() + 1) : (today.getMonth() + 1);
document.write("<BR>Time: ", today.getHours(), ":", today.getMinutes());
document.write("<BR>Date: ", today.getDate(), "/", month, "/", today.getYear() - 100);

jsFiddle example

Pointy
  • 405,095
  • 59
  • 585
  • 614
j08691
  • 204,283
  • 31
  • 260
  • 272
1

A different way of padding with zeros

function zfill(str, len) {
    var i = len - (''+str).length + 1;
    if (i > 0) return new Array(i).join('0') + str;
    return ''+str;
}

Then

zfill(5, 2); // "05"
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

Try this:

var d = new Date();
var month = d.getMonth()+1;
if (month.toString().length!==2) { month="0"+month; }
SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59