gpt4 book ai didi

javascript - 返回距离现在最近的时间的项目 JavaScript/Moment.js

转载 作者:行者123 更新时间:2023-12-03 02:08:48 26 4
gpt4 key购买 nike

我正在开发一个与日志和时间相关的应用程序。我有这个带有对象(日志)的数组。我想找到 checkin_time (这是对象的属性)最接近现在的对象。因此,如果我有两个对象,一个具有“2018-04-05 08:04:12”的 checkin_time ,另一个具有“2018-04-05 10:02:12”,我想找到带有“2018-04-05 10:02:12”的对象,因为那个时间是距现在最近的时间。

我尝试使用 Moment.js 库进行一些操作,但没有成功。我正在使用Vue框架。

更新

我已经尝试了下面的答案之一,但仍然没有定义。有什么我没看到的吗?

代码

methods: {
getLog() {


this.users.forEach(element => {

element.logs.forEach((log) => {

this.Logs.push(log);

})

});

var unfinished = this.Logs.filter((log) => {
return log.finished == false;
});

console.log(unfinished);

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.
]

console.log(input);

// Closest From Now.
const closestFromNow = times => times.filter(x => Date.now() < new Date(x.checkin_time)).sort((a, b) => new Date(a.checkin_time)*1 - new Date(b.checkin_time)*1)[0]

// Output.
const output = closestFromNow(unfinished)
const output2 = closestFromNow(input)

// Proof.
console.log(output) // Undefined
console.log(output2) // ID 2. 8 AM.


}
}

enter image description here

最佳答案

参见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.

关于javascript - 返回距离现在最近的时间的项目 JavaScript/Moment.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49670727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com