我正在处理与日志和时间相关的应用程序。我有这个数组与对象(日志)。我想找到最接近现在的checkin_time
(来自对象的属性)的对象。所以,如果我有两个对象,一个来自" 2018-04-05 08:04:12" " 2018-04-05 10:02:12"我想找到对象" 2018-04-05 10:02:12"因为那是从现在起最近的时间。
我尝试使用Moment.js库,但这并没有成功。我正在使用Vue框架。
更新
我已经尝试过下面的一个答案,但我仍然未定义。有什么东西我不明白吗?
代码
checkin_time
答案 0 :(得分:1)
有关详细信息,请参阅Map
,Math.min()
和Math.abs()
。
// Input.
const input = [
{id: 1, checkin_time: "2030-05-05 16:22:02"}, // 4 PM MAY 5 2030.
{id: 2, checkin_time: "2030-05-05 08:22:02"}, // 8 AM MAY 5 2030.
{id: 3, checkin_time: "2000-05-05 13:22:02"}, // 1 PM MAY 5 2030.
{id: 4, checkin_time: "2000-05-05 11:22:02"}, // 11 AM MAY 5 2030.
]
// Is Before Now
const isBeforeNow = x => (Date.now() > x)
// Generate Key.
const generateKey = x => Math.abs(Date.now()*1 - x*1)
// Closest From Now.
const closestFromNow = (times, restriction) => {
const m = new Map(times.map(x => {
let date = new Date(x.checkin_time)
if (restriction == 'before') {
if (isBeforeNow(date)) date = generateKey(date)
else date = undefined
}
else if (restriction == 'after') {
if (!isBeforeNow(date)) date = generateKey(date)
else date = undefined
}
else {
date = generateKey(date)
}
return [date, x]
}))
m.delete(undefined)
return m.get(Math.min(...m.keys()))
}
// Proof.
console.log('Closest Before Now', closestFromNow(input, 'before')) // ID 3.
console.log('Closest After Now', closestFromNow(input, 'after')) // ID 2.
console.log('Closest From Now In General 1', closestFromNow(input)) // ID 3.
console.log('Closet From Now In Generate 2', closestFromNow([...input, {id: 11, checkin_time: "2020-05-05 11:22:02"}])) // ID 11.

答案 1 :(得分:0)
methods: {
getLog() {
var bigestElem = null;
var closestTime = 0;
var elemTime = 0;
this.users.forEach(element => {
element.logs.forEach((log) => {
elemTime = new Date(log.checkin_time).getTime()
if(log.finished === false && elemTime > closestTime){
closestTime = elemTime;
bigestElem = log;
}
this.Logs.push(log);
})
});
console.log(bigestElem);
return bigestElem
}
},
答案 2 :(得分:0)
您可以创建一个辅助函数:
const input = [
{id: 1, checkin_time: "2030-05-05 10:22:02"}, // 10 AM.
{id: 2, checkin_time: "2030-05-05 08:22:02"} // 8 AM.
]
function findNearestTime(times){
let currentTime = Date.now();
let diff = times.map(time => {
return Math.abs(currentTime - Date.parse(time.checkin_time));
})
let i = diff.indexOf(Math.min(...diff));
return times[i].checkin_time;
}
let latest = findNearestTime(input);
alert("nearest time is :" + latest)