Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  145] [ 4]  / answers: 1 / hits: 90356  / 13 Years ago, sun, january 29, 2012, 12:00:00
var date = Fri Jan 29 2012 06:12:00 GMT+0100;


How can i show this in format 2012-01-29 06:12 ?
In PHP is function ->format. In Javascript is also format, but if i try use this then i have error:



now.format is not a function



var now = new Date();
console.log(now.format(isoDateTime));


http://jsfiddle.net/6v9hD/



I would like receive format: 2012-01-29 06:12


More From » jquery

 Answers
1

This question is a duplicate (see: How to get current date in jquery?).



By modifying my solution from the other question, I got:



var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();

var output = d.getFullYear() + '-' +
((''+month).length<2 ? '0' : '') + month + '-' +
((''+day).length<2 ? '0' : '') + day + ' ' +
((''+hour).length<2 ? '0' :'') + hour + ':' +
((''+minute).length<2 ? '0' :'') + minute + ':' +
((''+second).length<2 ? '0' :'') + second;


See this jsfiddle for a proof: http://jsfiddle.net/nCE9u/3/



You can also enclose it within function (demo is here: http://jsfiddle.net/nCE9u/4/):



function getISODateTime(d){
// padding function
var s = function(a,b){return(1e15+a+).slice(-b)};

// default date parameter
if (typeof d === 'undefined'){
d = new Date();
};

// return ISO datetime
return d.getFullYear() + '-' +
s(d.getMonth()+1,2) + '-' +
s(d.getDate(),2) + ' ' +
s(d.getHours(),2) + ':' +
s(d.getMinutes(),2) + ':' +
s(d.getSeconds(),2);
}


and use it like that:



getISODateTime(new Date());


or:



getISODateTime(some_other_date);


EDIT: I have added some improvement to the function, as proposed by Ates Goral (also decreased its readability in favour of code comments).


[#87754] Thursday, January 26, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;