完整代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时间戳</title>
</head>
<body>
<script>
//添加0的方法
function addZero(num) {
num = num.toString();
return num[1] ? num : "0" + num;
}
// console.log(addZero(5));
function fmtTime(str) {
let now = new Date();
let thatTime = new Date(str);
//now - thatTime 结果为相差的毫秒数,
let totalSec = Math.floor((now - thatTime) / 1000); //获得秒钟
if (totalSec < 60) return "刚刚";
//1小时以内显示多少分钟前
else if (totalSec < 60 * 60) return Math.floor(totalSec / 60) + "分钟前";
//1天以内显示多少小时前
else if (totalSec < 60 * 60 * 24) return Math.floor(totalSec / 60 / 60) + "小时前"
//大于一天则显示具体的时间
else return [thatTime.getFullYear(), addZero(thatTime.getMonth() + 1),
addZero( thatTime.getDate())
].join("-") + " " + [addZero(thatTime.getHours()), addZero(thatTime.getMinutes()), addZero(thatTime.getSeconds())].join(":");
}
console.log(fmtTime("2019-08-01 8:10:59"))
</script>
</body>
</html>