封装时间戳转换成时间格式(基础版)(如:YYYY-MM-DD hh:mm:ss)

时间戳转换工具 :https://tool.lu/timestamp

1.时间戳转成对应自定义时间格式(如:YYYY-MM-DD hh:mm:ss)

<script>
	function timeStamp(t){
     
     
		let date = new Date(t)
		let Y = date.getFullYear();
		let M = date.getMonth()+1 <10 ? '0' + date.getMonth()+1 :date.getMonth()+1;
		let D = date.getDate() <10 ? '0' + date.getDate() : date.getDate();
		let H = date.getHours() <10 ? '0' + date.getHours() : date.getHours();
		let Mi = date.getMinutes() <10 ? '0' + date.getMinutes() : date.getMinutes();
		let S = date.getSeconds() <10 ? '0' + date.getSeconds() : date.getSeconds();
		let tempDate = `${
       
       Y}-${
       
       M}-${
       
       D} ${
       
       H}${
       
       Mi}${
       
       S}`;
		return tempDate ;
}

console.log("时间戳转换后:", timeStamp(844876800000))
</script>

在这里插入图片描述
2.去掉形参,获取当前时间后转换成(如:YYYY-MM-DD hh:mm:ss)自定义时间格式

<script>
function nowTime() {
     
     
			let date = new Date();
			let Y = date.getFullYear();
			let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
			let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
			let H = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
			let Mi = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
			let S = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
			let tempDate = Y + '-' + M + '-' + D + ' ' + H + ':' + Mi + ':' + S;
			return tempDate;
		}
		console.log("时间戳转换后:", nowTime())

</script>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45695853/article/details/115227080