JS格式化日期时间、获取指定时间

/*
 * @description 格式化日期时间
 * @demo dateFormat(new Date(), 'yyyy-MM-dd HH:mm:ss')
 * @method dateFormat
 * @param {Date} d 时间
 * @param {String} str 格式,默认'yyyy-MM-dd HH:mm:ss'
 * @return {String} 格式化的时间
*/
function dateFormat(d, str) {
    var formatStr = checkNull(str) ? 'yyyy-MM-dd HH:mm:ss' : str;
	
	if (checkNull(d)) { // 如果日期为空,自动获取当前日期
		d = new Date();
	} else if (d.constructor != Date) { // 如果参数不是一个日期对象,就认为是一个标准Long值日期
		d = new Date(d);
	}
	
	return formatStr .replace("yyyy", d.getFullYear())
		.replace("MM", fillZero(d.getMonth() + 1))
		.replace("dd", fillZero(d.getDate()))
		.replace("HH", fillZero(d.getHours()))
		.replace("mm", fillZero(d.getMinutes()))
		.replace("ss",fillZero(d.getSeconds()))
		.replace("sss", d.getMilliseconds());
		
	// 填充0
	function fillZero(value) {
		return value.toString().length < 2 ? ('0' + value) : value
	}
}

/*
 * @description 获取指定时间
 * @demo targetDate({type: 'week', num: 2});
 * @method targetDate
 * @param {Object} options {num: Number, date: Date, format: String , type: String }
 * @return {String} 格式化的时间
*/
function targetDate(options) {
	var date,
		num = parseInt(options.num) || 0,
		format = options.format || 'yyyy-MM-dd HH:mm:ss';
	
	if (checkNull(options.date)) { // 如果日期为空,自动获取当前日期
		date = new Date();
	} else if (options.date.constructor !== Date) { // 如果参数不是一个日期对象,就认为是一个标准Long值日期
		date = new Date(options.date);
	}
		
	switch (options.type) {
		case "day":
			date.setDate(date.getDate() + num);
			return dateFormat(date, format);
			
		case "week":
			date.setDate(date.getDate() + num * 7);
			return dateFormat(date, format);
			
		case "month":
			date.setMonth(date.getMonth() + num);
			return dateFormat(date, format);
			
		case "year":
			date.setFullYear(date.getFullYear() + num);
			return dateFormat(date, format);
			
		case "hours":
			date.setHours(date.getHours() + num);
			return dateFormat(date, format);
			
		case "minutes":
			date.setMinutes(date.getMinutes() + num);
			return dateFormat(date, format);
			
		case "seconds":
			date.setSeconds(date.getSeconds() + num);
			return dateFormat(date, format);
			
		default:
			throw new Error('type值应为day、week、month、year、hours、minutes、seconds其中一个')
	}
}

/*
 * @description 判空
 * @demo checkNull('')
 * @method checkNull
 * @param {any} value 需要校验的字符串
 * @return {Boolean} true/false
*/
function checkNull(value) {
    return (!value || value == null || typeof(value) == "undefined" || value == "");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值