js-格式化时间

1.作用:该工具类用来格式化日期
2.含义:参数date:要格式化的时间;format:转换的日期格式
3.示例:将时间戳转换为’yyyy-MM-dd’日期格式。调用下面的函数formatDate(1541430824000, ‘yyyy-MM-dd’)
4.转换结果:“2018-11-05”

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]];
	});
}

猜你喜欢

转载自blog.csdn.net/rongxiang111/article/details/83758753