JS/TS date and time format conversion

/**
 * 转换时间格式
 * @param date 将转换的时间
 * @param fmt 转换成的格式 yyyy-MM-dd|yyyy-MM-dd hh:mm:ss
 */
const DateFormat = (date: string, fmt: string): string => {
    
    
	if (date && fmt) {
    
    
		let _date = new Date(date);
		var o = {
    
    
			'M+': _date.getMonth() + 1, //月份
			'd+': _date.getDate(), //日
			'h+': _date.getHours(), //小时
			'm+': _date.getMinutes(), //分
			's+': _date.getSeconds(), //秒
			'q+': Math.floor((_date.getMonth() + 3) / 3), //季度
			S: _date.getMilliseconds(), //毫秒
		};
		if (/(y+)/.test(fmt)) {
    
    
			fmt = fmt.replace(RegExp.$1, (_date.getFullYear() + '').substr(4 - RegExp.$1.length));
		}
		for (var k in o) {
    
    
			if (new RegExp('(' + k + ')').test(fmt)) {
    
    
				fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? (o as any)[k] : ('00' + (o as any)[k]).substr(('' + (o as any)[k]).length));
			}
		}
		return fmt;
	} else {
    
    
		return '';
	}
};

let newDate='2022-09-06T15:48:27.239+08:00';
let D1=DateFormat(newDate, 'yyyy-MM-dd');
let D2=DateFormat(newDate, 'yyyy-MM-dd hh:mm:ss');
console.log(D1,D2);

Guess you like

Origin blog.csdn.net/u010100877/article/details/126835480