Reputation: 137
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
Upvotes: 0
Views: 87
Reputation: 121
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!
Upvotes: 0
Reputation: 29630
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');
Upvotes: 2
Reputation: 324800
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())+"/"+.....
Upvotes: 1