3

原生JS实现两个时间相隔时长,自适应天时分秒

 2 years ago
source link: https://www.fly63.com/article/detial/11227
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
更新日期: 2022-02-25阅读量: 44标签: 时间分享

扫一扫分享

从因为一个小需求,我浪费了将近两个小时去百度,但是却没有找到想要的结果,不知道是因为我搜索的能力下降了还是搜索引擎不好使了,我还去专门看了dayjs,moment的文档,想着后面可能用到的地方还挺多直接用api也挺方便,可惜找来找去也没有自己想要的答案,索性自己写一个吧。其实需求也很简单(就是自己懒),就是展示两个时间的时间差,也就是时长展示,效果大概就是(1天5时3分20秒),不足某个单位则省略。

不需要准备啥,主要就是需求搞清楚就行了,先计算两个时间的时间差,然后从天除到秒,因为我这个主要是展示脚本执行时间,所以就只做到天,当然要做到年月也是可以的。

代码

function timeDuration(start, end) {
// 这里可以判断一下start,end是否能转换成时间,因为懒所以没做~
const diffSeconds = new Date(end).getTime() / 1000 - new Date(start).getTime() / 1000;
if (!diffSeconds || diffSeconds < 0) return '0秒';
let leftSeconds, resultStr = '';
resultStr += diffSeconds / 86400 > 1 ? Math.floor(diffSeconds / 86400) + '天' : '';
leftSeconds = diffSeconds % 86400;
resultStr += leftSeconds / 3600 > 1 ? Math.floor(leftSeconds / 3600) + '时' : '';
leftSeconds = diffSeconds % 3600;
resultStr += leftSeconds / 60 > 1 ? Math.floor(leftSeconds / 60) + '分' : '';
leftSeconds = diffSeconds % 60;
resultStr += leftSeconds + '秒';
return resultStr;
}

其实呢,这段代码真的很简单,起初就是因为懒,所以总结一下主要就是遇到问题的时候先思考一下时间成本,不要因为问题简单就以为网上可以很容易找到,其实网上是有的(以前有印象),但是现在找不到了,所以我就花了很多时间去找,本以为很容易找到,可以省写的时间,结果浪费了那么久,唉,所以这也算是一种教训啊,时间成本很贵的,尤其是忙的飞起的时候!

来自:https://www.cnblogs.com/jieli/archive/2022/02/24/timeDuration.html

链接: https://www.fly63.com/article/detial/11227


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK