Reputation: 11984
I am getting values from database which is a time stamp.And i need to convert it into mm/dd/yyyy H:i:s using javascript. i tried the following code. but its not working it firefox/ie.But its working in chrome..how to solve it.
function formatDate(value){
if(value){
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(value),
dformat = [ (d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}
I am getting NaN/NaN/NaN/NaN/NaN/NaN in firefox and ie.Any help is much appreciated
Upvotes: 2
Views: 10504
Reputation: 9211
Your code is missing a trailing }
. If you formatted it better, you would see this:
function formatDate(value){
if(value){
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(value),
dformat = [ (d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}
}
It works fine in Firefox, now.
Note that you are defining Number.prototype.padLeft
each time you call this function. It would be better to move this out of the function body.
EDIT As per my comment, the reason this is failing for you is that the Date
object will only accept strings in certain formats. Moreover, it occurs to me that your function is just changing the format of a string: You don't really need to bother messing about with dates and, instead, just do string operations on your input:
var formatDate = function(dateString) {
// Convert 'yyyy-mm-dd hh:mm:ss' to 'mm/dd/yyyy hh:mm:ss'
return dateString.replace(/^(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1');
};
Much easier!
Upvotes: 6
Reputation: 479
function formatDate(d)
{
d = new Date(d * 1000);
return d.getMonth() + 1 + '/' + d.getDate() + '/' + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
Upvotes: 1
Reputation: 329
Javascript already know how to work with a timestamp.
var d = new Date(timestamp * 1000); //will create a date object
You then can use all the Javascript Date methods to format it. (http://www.w3schools.com/jsref/jsref_obj_date.asp)
EDIT : Convert timestamp to milliseconds (*1000)
Upvotes: 0