关于时间戳与格式日期的转换

知道一月中某天时间戳,获取该月1日至30日时间戳

function computeTime(time){
    const y = new Date(time).getFullYear();
	const m = new Date(time).getMonth()+1;
	return [new Date(y, m - 1, 1).getTime(),new Date(y, m, 0).getTime()];
}
computeTime(time);

将时间戳转换为指定日期格式

function format(date,format){
			let time;
			if(date instanceof Date){
				time = date;
			}else{
				time = new Date(date);
			}
			const o = {
				'M+':time.getMonth()+1,
				'd+':time.getDate(),
				'h+':time.getHours(),
				'm+':time.getMinutes(),
				's+':time.getSeconds(),
				'q+':Math.floor((time.getMonth()+3)/3),
				S:time.getMilliseconds(),
			};
			if(/(y+)/.test(format)){
				format = format.replace(RegExp.$1,(`${time.getFullYear()}`).substr(4-RegExp.$1.length));
			}
			for(const 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;
		}
        let date = new Date().getTime();
		console.log(date,format(date,'yyyy年MM月dd'))

猜你喜欢

转载自blog.csdn.net/qq_42758038/article/details/86674079
今日推荐