js time conversion format

Time format conversion method

 Applicable formats :

yyyy / yyyy-mm / yyyy-mm-dd / yyyy-mm-dd hh:mm:ss /

Date.prototype.format = function(format) {
	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 ChangeDateType(TM, TMformat) {
	let result = TM;
	try {
		result = TM.format(TMformat);
	} catch (e) {
		//TODO handle the exception
	};
	return result;
}
export default ChangeDateType;

How to use :
 import ChangeDateType from "../../路径";
  // 倒推时间 
  let nowTM = new Date();
  // -30 意为倒推30天
  let lastTM = new Date(nowTM.setDate(nowTM.getDate() - 30));
  // 使用时将获取的日期传入方法,并将日期格式传输。 
  // 此时回执便是倒推30天日期 如果传入 new Date() 日期便是今日 
  let beginTM = ChangeDateType(lastTM, 'yyyy-MM-dd');
  let endTM = ChangeDateType(new Date(), 'yyyy-MM-dd');

The following code is an excerpt from the network. The original address is lost. It’s true. Sorry.

Date.prototype.format = function(format) {
	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;
};

Guess you like

Origin blog.csdn.net/weixin_70862058/article/details/130844870