+
95
-

js中距离当前时间 刚刚、n分钟前、n小时前、昨天、2天前、3天前、具体日期(月-日 / 年-月-日)怎么实现的?

请问js中距离当前时间 刚刚、n分钟前、n小时前、昨天、2天前、3天前、具体日期(月-日 / 年-月-日)怎么实现的?

网友回复

+
15
-

直接根据秒来判断,代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">

    <script type="text/javascript">

        function getTimeDistance(time) {
            // 支持传入10位或13位毫秒数,如 1587367194536,"1587367194"
            // 支持传入日期格式,如 "2020/4/20 15:31:18"

            if (typeof time == "number" || Number(time) == time) {
                if (String(time).length == 10) {
                    time = Number(time) * 1000
                } else if (String(time).length == 13) {
                    time = Number(time)
                } else {
                    console.log("时间格式错误");
                    return time;
                }
            } else {
                if (typeof time == "string" && time.split(" ").length == 2 && time.split(/[- : \/]/).length == 6) {
                    time = new Date(time.replace(/\-/g, '/')).getTime();
                } else {
                    console.log("时间格式错误");
                    return time;
               ...

点击查看剩余70%

我知道答案,我要回答