[Javascript]日期的格式化和解析

2021-01-19 792点热度 0人点赞 0条评论

分享自用的JS日期格式化和字符串解析成日期的工具方法

/**
 * 时间对象的格式化
 */
Date.prototype.format = function(format) {
	/*
	 * eg:format="yyyy-MM-dd HH:mm:ss";
	 */
	var o = {
		"M+" : this.getMonth() + 1, // month
		"d+" : this.getDate(), // day
		"H+" : this.getHours(), // hour
		"m+" : this.getMinutes(), // minute
		"s+" : this.getSeconds(), // second
		"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
		"S" : this.getMilliseconds()
	// millisecond
	};

	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}

	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
};

/**
 * 字符串解析成时间格式
 */
function parseDate(s) {
	return new Date(Date.parse(s.replace(/-/g, "/")));
}

如何使用

var date = parseDate('2021-01-19 00:00')
//格式可以是yyyy-MM-dd HH:mm:ss
var dateString = date.format("yyyy-MM-dd")

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论