您的位置:首页 > Web前端 > JavaScript

js中格式化时间字符串

2014-08-20 19:01 309 查看
.net 程序员肯定有遇到过,将一个对象json序列化之后Date 字段 就会转化成 '/Date(1370770323740)/' 这种格式的数据,下面介绍一种在js中,关于时间格式的转换。

<script>
function formatDate(date, format) {
if (!date) return;
if (!format) format = "yyyy-MM-dd";
switch(typeof date) {
case "string":
date = new Date(date.replace(/-/, "/"));
break;
case "number":
date = new Date(date);
break;
}
if (!date instanceof Date) return;
var dict = {
"yyyy": date.getFullYear(),
"M": date.getMonth() + 1,
"d": date.getDate(),
"H": date.getHours(),
"m": date.getMinutes(),
"s": date.getSeconds(),
"MM": ("" + (date.getMonth() + 101)).substr(1),
"dd": ("" + (date.getDate() + 100)).substr(1),
"HH": ("" + (date.getHours() + 100)).substr(1),
"mm": ("" + (date.getMinutes() + 100)).substr(1),
"ss": ("" + (date.getSeconds() + 100)).substr(1)
};
return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function() {
return dict[arguments[0]];
});
}

alert(formatDate("2010-04-30", "yyyy-MM-dd HH:mm:ss"));
alert(formatDate("2010-4-29 1:50:00", "yyyy-MM-dd HH:mm:ss"));
</script>


var datestr="/Date(1408291200000+0800)/"; //模拟我们返回的json日期格式

var newdate=eval(datastr.replace(/\//g, '')); // 通过这个方法日期被格式化成了"Wed Aug 20 2014 18:54:10 GMT+0800 (中国标准时间)"标准时间格式


然后在调用上面的方法:

alert(formatDate(newdate, "yyyy-MM-dd HH:mm:ss"));
alert(formatDate(newdate, "yyyy-MM-dd"));


返回结果:  2014-08-20 19:00:13

     2014-08-20  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: