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
  • 222,134
  • 40
  • 319
  • 330
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
  • 52,378
  • 28
  • 138
  • 145
mplungjan
  • 155,085
  • 27
  • 166
  • 222
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
  • 389,373
  • 58
  • 564
  • 602
j08691
  • 197,815
  • 30
  • 248
  • 265
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.
  • 61,621
  • 8
  • 116
  • 132
0

Try this:

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