js计算两个日期相差多少年

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<input type="text" name="startDate" value="" placeholder="" />
<input type="text" name="endDate" value="" placeholder="" />
<input type="button" name="sub" value="计算" onclick="getDateYearSubNew()" /><br />
<input type="text" name="result" value="" placeholder="" />
</div>

<script type="text/javascript">
// var d = getDateYearSub("2017-02-22","2018-02-22");
// console.log(d);
function getDateYearSubNew() {
// debugger;
var day = 24 * 60 * 60 * 1000;

var startDateStr = document.getElementsByName('startDate')[0].value;
var endDateStr = document.getElementsByName('endDate')[0].value;

var sDate = new Date(Date.parse(startDateStr.replace(/-/g, '/')));
var eDate = new Date(Date.parse(endDateStr.replace(/-/g, '/')));

var result = document.getElementsByName('result')[0];

//获得各自的年、月、日
var sY = sDate.getFullYear();
var sM = sDate.getMonth() + 1;
var sD = sDate.getDate();
var eY = eDate.getFullYear();
var eM = eDate.getMonth() + 1;
var eD = eDate.getDate();

var yL = eY - sY;
var mL = eM - sM;
var dL = eD - sD;
console.log('年相差:' + yL);
console.log('月相差:' + mL);
console.log('日相差:' + dL);
if (dL < 0) {
mL--;
}
if (mL < 0) {
yL--;
}
if (yL > 0) {
result.value = yL;
} else {
result.value = 0;
}
}
</script>
</body>
</html>
posted @ 2023-02-05 18:49  外行的小白  阅读(1226)  评论(0编辑  收藏  举报