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

js格式化时间

2015-07-29 13:10 465 查看
/*
* date 需要格式化的时间
* farmatStr 需要格式化的样式 如:yyyy-MM-dd
*/
function dateFormat(date,formatStr){

// 转换成Date类型
var date = new Date(date);
var opt = {
'yyyy': date.getFullYear(),
'MM': addZero(date.getMonth() + 1),
'M': date.getMonth() + 1,
'dd': addZero(date.getDate()),
'd': date.getDate(),
'hh': addZero(date.getHours()),
'h': date.getHours(),
'mm': addZero(date.getMinutes()),
'm': date.getMinutes(),
'ss': addZero(date.getSeconds()),
's': date.getSeconds()
};

// 如果是个位数则前面添加0
function addZero(value){
return value < 10 ? '0'+value : value;
}

// 遍历替换
for(var k in opt){
formatStr = formatStr.replace(k,opt[k]);
}

return formatStr;
}

如何使用:
dateFormat('2014-2-3','yyyy-MM-dd');
得到 "2014-02-03"

dateFormat(new Date(),'yyyy-MM-dd');
得到当前时间


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