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>


转载于:https://www.cnblogs.com/duke-cui/p/11099115.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值