JS日期格式化(支持格式YYYY-MM-DD,HH:MM:SS,YYYY-MM-DD HH,YYYY-MM-DD HH:MM:SS)

JS日期格式化(支持格式YYYY-MM-DD,HH:MM:SS,YYYY-MM-DD HH,YYYY-MM-DD HH:MM:SS)

function formatDate(date, format) {
	if (date != null && format != null && format != "") {
		var nowDate = new Date(date);
		var year = nowDate.getFullYear();
		var month = nowDate.getMonth() + 1 < 10 ? "0"
				+ (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
		var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
				.getDate();
		var hours = nowDate.getHours() < 10 ? "0" + nowDate.getHours()
				: nowDate.getHours();
		var minutes = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes()
				: nowDate.getMinutes();
		var seconds = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds()
				: nowDate.getSeconds();
		if (format.toUpperCase() == "YYYY-MM-DD") {
			return year + "-" + month + "-" + date;
		} else if (format.toUpperCase() == "YYYY-MM-DD HH:MM:SS") {
			return year + "-" + month + "-" + date + " " + hours + ":"
					+ minutes + ":" + seconds;
		}else if (format.toUpperCase() == "HH:MM:SS") {
			return hours + ":"+ minutes + ":" + seconds;
		}else if (format.toUpperCase() == "YYYY-MM-DD HH") {
			return year + "-" + month + "-" + date + " " + hours ;
			
		}
	} else {
		return null;
	}
}

猜你喜欢

转载自blog.csdn.net/u010210963/article/details/107489565