lgwebdream / FE-Interview

🔥🔥🔥 前端面试,独有前端面试题详解,前端面试刷题必备,1000+前端面试真题,Html、Css、JavaScript、Vue、React、Node、TypeScript、Webpack、算法、网络与安全、浏览器
https://lgwebdream.github.io/FE-Interview/
Other
6.76k stars 897 forks source link

Day337:输入一个日期,返回几秒前、几小时前、几天前、几月前 #1167

Open Genzhen opened 2 years ago

Genzhen commented 2 years ago

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案 欢迎大家在下方发表自己的优质见解

二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

lzdml commented 2 months ago

`function relativeTime(date) { const now = Date.now(); const diff = now - date.getTime();

const units = [
    { label: "秒", divisor: 1000 },
    { label: "分钟", divisor: 60 },
    { label: "小时", divisor: 60 },
    { label: "天", divisor: 24 },
    { label: "月", divisor: 30 },
];

for (const unit of units) {
    if (diff < unit.divisor) {
        return Math.floor(diff / (unit.divisor / 1000)) + unit.label + "前";
    }
    diff /= unit.divisor;
}

return "很久以前";

}`