JS 時間戳轉日期格式

1、日期轉換為時間戳,(如果日期格式為時間戳,將其轉為日期類型,否則輸出傳入的數據)
	// 如果時間格式為時間戳,將其轉為日期
	function timestampToDate(timestamp) {
		
		// 將數據類型轉為字符串
		if (timestamp && /^[0-9]*[0-9][0-9]*$/.test(timestamp) && (timestamp.toString().length == 10 || timestamp.toString().length == 13)) {
			
			timestamp = parseInt(timestamp);
			
			if (timestamp.toString().length == 10) {
				
				timestamp = timestamp * 1000;
			}
		
			var date = new Date(timestamp);
			
			Y = date.getFullYear();
			M = (date.getMonth() + 1 < 10 ? '0'+(date.getMonth() + 1) : date.getMonth() + 1);
			D = date.getDate();
			
			return Y+"-"+M+"-"+D;
		}
		
		return timestamp;
	}

2、時間戳轉換為日期

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Date对象</title>
</head>
<body>
	<script>
	 
	var date = new Date(1398250549123); //传个时间戳过去就可以了
	Y = date.getFullYear() + '-';
	M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
	D = date.getDate() + ' ';
	h = date.getHours() + ':';
	m = date.getMinutes() + ':';
	s = date.getSeconds()+ ':'; 
	ss = date.getMilliseconds();

	console.log(Y+M+D+h+m+s+ss);  //2014-04-23 18:55:49:123
		
	</script>
</body>
</html>

日期轉換為時間戳

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Date对象</title>
</head>
<body>
	<script>
	 
	  var date = new Date('2014-04-23 18:55:49:123');//可以传时间,也可以不传,不传的话就是默认的当前时间
	  time1 = date.getTime(); 
	  time2 = date.valueOf();
      time3 = Date.parse(date);

	  console.log(time1);  //1398250549123
	  console.log(time2);  //1398250549123
	  console.log(time3);  //1398250549000
		
	</script>
</body>


posted @ 2017-11-10 15:32  Duke-码动青春  阅读(270)  评论(0编辑  收藏  举报