如何将mysql时间戳格式化为mm / dd / yyyy H:i:s在javascript中 [英] how to format mysql timestamp into mm/dd/yyyy H:i:s in javascript
问题描述
我从数据库中获取值是时间戳。我需要将其转换为mm / dd / yyyy H:i:s使用javascript。我尝试了以下代码。但它没有工作它firefox / ie.But它的工作在chrome..how解决它。
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;
}
我在Firefox中获得NaN / NaN / NaN / NaN / NaN / NaN非常感谢
I am getting NaN/NaN/NaN/NaN/NaN/NaN in firefox and ie.Any help is much appreciated
推荐答案
您的代码缺少尾随}
。如果你更好地格式化它,你会看到:
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;
}
}
现在在Firefox中运行良好。
It works fine in Firefox, now.
请注意,每次调用此函数时都要定义 Number.prototype.padLeft
。最好将其移出功能体。
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.
编辑根据我的说法注释,这个失败的原因是 Date
对象只接受某些格式的字符串。此外,我发现你的函数只是改变了一个字符串的格式:你真的不需要麻烦日期,而只是在你的输入上做字符串操作:
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');
};
更容易!
这篇关于如何将mysql时间戳格式化为mm / dd / yyyy H:i:s在javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!