0

I am using a function to log some stuff that happens in the background and this is the code I use to get the date and hour, etc.

function fStartLog() {

    var oDate = new Date();
    var sDate = oDate.getDate() +"/"+ oDate.getMonth() +"/"+ oDate.getFullYear() +" - "+ oDate.getHours() +":"+ oDate.getMinutes() +":"+ oDate.getSeconds();

    console.log("["+ sDate +"] mysite.com > Loading DONE!");

}

My question is, how can I get the date in a format with zeroes. Example:

[WRONG] 5/7/2013 - 22:5:9
[GOOD]    05/07/2013 - 22:05:09

MoeSzislak
  • 127
  • 1
  • 2
  • 13
  • See http://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-leng – Andy Jones Jul 19 '13 at 20:24
  • Possible duplicate of [How to format a JavaScript date](http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – John Slegers Feb 19 '16 at 21:46

3 Answers3

2

You can also use moment.js. It's extemely powerful.

I believe something like this would give you what you need.

moment().format('L[ - ]hh:mm:ss');
arturomp
  • 26,187
  • 10
  • 39
  • 64
  • Should I download the "mini" version? Will that work with your example? – MoeSzislak Jul 19 '13 at 20:30
  • From my understanding, the only difference is that the the source is minified (http://en.wikipedia.org/wiki/Minification_(programming)), but the syntax should be the same, so: yes :) – arturomp Jul 19 '13 at 21:43
1

I like to use a simple helper function: pad=function(n){return n<10?"0"+n:n;};

Then you can do sDate = pad(oDate.getDate())+"/"+.....

Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
0

Basically, if you convert the numbers returned from the date methods to a string and check the length, you can add a zero...

function fStartLog() {

    var oDate = new Date();

    var dd = oDate.getDate().toString();
    if (dd.length == 1) {
        dd = "0" + dd;
    }

    var mm = oDate.getMonth().toString();
    if (mm.length == 1) {
        mm = "0" + mm;
    }

    var sDate = dd +"/"+ mm +"/"+ oDate.getFullYear() +" - "+ oDate.getHours() +":"+ oDate.getMinutes() +":"+ oDate.getSeconds();

    console.log("["+ sDate +"] mysite.com > Loading DONE!");
}

Cheers!

Jim Elrod
  • 121
  • 6
  • That is a good answer but isn't it a bit redundant to make a function per each value? (minute, hour, day, etc) For instance, take a look at the answer of Kolink... it works perfectly only with a function. Thanks! – MoeSzislak Jul 19 '13 at 20:35