前言
记录一下前端的小技巧,如何计算两个时间点相差多少年?
要求如下:
(1)最多保留小数点后两位;
(2)若小数点后两位都为0,则不要小数,取整;
(3)若小数点的第一位非0,第二位为0,则不要第二位的小数;
一、示例代码
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<h1>计算两个时间点相差多少年</h1>
</body>
<script type="text/javascript">
/**
* 获取两个时间点相差多少年
*/
function getYearDiff(startDate, endDate) {
return Math.abs(new Date(startDate).getTime() - new Date(endDate).getTime()) / (1000 * 3600 * 24 * 365)
}
/**
* 格式化年差异数值
*/
function formatYearDiff(yearDiff) {
return Number(yearDiff.toString().match(/^\d+(?:\.\d{0,2})?/))
}
const startDate = '2021-07-28'
const endDate = '2023-06-12'
let yearDiff = getYearDiff(startDate, endDate)
console.log('格式化前 =>', yearDiff)
console.log('格式化后 =>', formatYearDiff(yearDiff))
</script>
<script type="text/javascript">
console.log('')
console.log('formatYearDiff(2.500010100) =>', formatYearDiff(2.500010100))
console.log('formatYearDiff(3.1415926) =>', formatYearDiff(3.1415926))
console.log('formatYearDiff(1.20) =>', formatYearDiff(1.20))
</script>
</html>
二、运行结果
2.500010100 => 2.5
3.1415926 => 3.14
1.20 => 1.2
10.00 => 10