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

2

3 Answers 3

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');
Sign up to request clarification or add additional context in comments.

2 Comments

Should I download the "mini" version? Will that work with your example?
From my understanding, the only difference is that the the source is minified (en.wikipedia.org/wiki/Minification_(programming)), but the syntax should be the same, so: yes :)
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())+"/"+.....

1 Comment

It works perfectly... the only thing is that the sDate string now is pretty large. But it works, thanks.
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!

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.