码迷,mamicode.com
首页 > Web开发 > 详细

js格式化时间

时间:2015-07-29 13:50:40      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

/*
* 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‘);
得到当前时间

  

js格式化时间

标签:

原文地址:http://www.cnblogs.com/scoprion/p/4685657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!