如何用JavaScript/Moment.js查找离当前时间最近的日志对象?
嘿,我懂你要解决的问题——从日志数组里找出checkin_time最接近当前时间的那条记录对吧?用Moment.js尝试没成功,我来给你分享两种靠谱的实现方式~
用Moment.js实现的方案
核心思路是计算每条日志的checkin_time与当前时间的时间差绝对值,然后找到差值最小的那条记录。Moment.js的diff方法可以直接帮我们计算时间差,非常省心。
// 假设你的日志数组是这样的 const logs = [ { checkin_time: "2018-04-05 08:04:12" }, { checkin_time: "2018-04-05 10:02:12" } ]; // 获取当前时间的Moment对象 const now = moment(); // 用reduce遍历数组,找出时间差最小的日志 const closestLog = logs.reduce((prevLog, currLog) => { // 计算每条日志与当前时间的时间差绝对值 const prevDiff = Math.abs(moment(prevLog.checkin_time).diff(now)); const currDiff = Math.abs(moment(currLog.checkin_time).diff(now)); // 保留差值更小的那条日志 return prevDiff < currDiff ? prevLog : currLog; }); console.log(closestLog); // 输出checkin_time为"2018-04-05 10:02:12"的对象
如果你的checkin_time格式比较特殊,Moment.js可能无法自动识别,这时候可以手动指定格式参数,比如:
moment(currLog.checkin_time, "YYYY-MM-DD HH:mm:ss")
原生JavaScript实现方案(不依赖库)
如果你不想依赖Moment.js,用原生Date对象也能搞定,核心逻辑和上面一致:
const logs = [ { checkin_time: "2018-04-05 08:04:12" }, { checkin_time: "2018-04-05 10:02:12" } ]; // 获取当前时间戳(毫秒) const nowTimestamp = Date.now(); const closestLog = logs.reduce((prevLog, currLog) => { // 把时间字符串转成Date对象(注意部分浏览器需要把空格换成T) const prevTimestamp = new Date(prevLog.checkin_time.replace(' ', 'T')).getTime(); const currTimestamp = new Date(currLog.checkin_time.replace(' ', 'T')).getTime(); // 计算时间差绝对值 const prevDiff = Math.abs(prevTimestamp - nowTimestamp); const currDiff = Math.abs(currTimestamp - nowTimestamp); return prevDiff < currDiff ? prevLog : currLog; }); console.log(closestLog);
一些注意事项
- 如果日志数组为空,
reduce方法会报错,所以最好先做个判断:if (logs.length === 0) { console.log('没有可用的日志数据'); return; } - 确保
checkin_time的格式是标准的日期时间格式,否则无论是Moment.js还是原生Date都可能解析失败。
内容的提问来源于stack exchange,提问作者Giesburts
相关产品推荐
相关产品推荐

