计算输入日期与当前日期的相差年份月份和天数

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#gap{
				display: inline-block;
				text-align: center;
				width:500px;
			}
			#TIME{
				display: inline-block;
				width:200px;
				text-align: center;
			}
		</style>
	</head>
	<body>
		<input type="text" name="" id="TIME" value="" />
		<input type="text" name="" id="USERTIME" value="" placeholder="输入要计算的时间" />
		<input type="button" name="" id="btn" value="计算与当前时间的差" onclick="fun2()" />
		<input type="text" name="" id="gap" value="" />
	</body>
</html>
<script type="text/javascript">
	function fun() {
		var d = new Date();
		var _y = d.getFullYear();
		var _m = toTwo(d.getMonth()+1);
		var _d = toTwo(d.getDate());
		var _h = toTwo(d.getHours());
		var _mm = toTwo(d.getMinutes());
		var _s = toTwo(d.getSeconds());
		var time = (_y + "年" + _m + "月" + _d + "日" + _h + "时" + _mm + "分" + _s + "秒");
		TIME.value = time;
	}
	setInterval(fun, 1000)
	function fun2() {
		var m = new Date();
		var _y = m.getFullYear();
		var _m = toTwo(m.getMonth()+1);
		var _d = toTwo(m.getDate());
		var _h = toTwo(m.getHours());
		var _mm = toTwo(m.getMinutes());
		var _s = toTwo(m.getSeconds());
		var time = (_y + "年" + _m + "月" + _d + "日" + _h + "时" + _mm + "分" + _s + "秒");
		// var USERTIME=document.getElementById("USERTIME");
		var str=USERTIME.value;//用户输入的时间
		var n = new Date(str);//将用户输入的时间计算出一个新的时间
		var sum=m-n//总共相差的时间
		var year=toTwo(parseInt((m-n)/(1000*60*60*24*30*12)));//相差的年份
		var month=toTwo(Math.round((m-n)/(1000*60*60*24*30)%12));//相差的月份
		var day=toTwo(Math.round((m-n)/(1000*60*60*24)%24));//相差的天数
		gap.value=USERTIME.value+"距离"+time+"相差大约"+year+"年"+month+"月"+day+"天";
	}
	function toTwo(v){
		return v<10?"0"+v:v;
	}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44963099/article/details/89738526
今日推荐