Javascript 如何将时间字符串(例如“8:02 AM”)转换为可排序字段

Javascript 如何将时间字符串(例如“8:02 AM”)转换为可排序字段,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我的MongoDB数据库现在包含时间作为字符串,我希望能够在特定时间之间过滤查询 例如,我的数据库中的时间字段看起来像“8:02 AM”和“10:20 PM”,我希望能够仅通过“8:00 AM”和“9:00 AM”之间的时间字段过滤结果。我的想法是将每个字符串转换为一个数字,即一天中的分钟,因此,例如,“9:00 AM”变为540和“10:20 PM”“变成1340,但必须有一种更有效的方法来做到这一点。我有什么明显的遗漏吗 我还尝试了JavaScriptDate(),但这假设我是EST,并将时

我的MongoDB数据库现在包含时间作为字符串,我希望能够在特定时间之间过滤查询

例如,我的数据库中的时间字段看起来像“8:02 AM”和“10:20 PM”,我希望能够仅通过“8:00 AM”和“9:00 AM”之间的时间字段过滤结果。我的想法是将每个字符串转换为一个数字,即一天中的分钟,因此,例如,“9:00 AM”变为540和“10:20 PM”“变成1340,但必须有一种更有效的方法来做到这一点。我有什么明显的遗漏吗

我还尝试了JavaScript
Date()
,但这假设我是EST,并将时间转换为我根本不想要的GMT

一些简陋的代码似乎有效,但我相信有更好的方法:

const time_function = (time) => {
    const split_string = time.replace(" ",":").split(":")
    if(split_string[0]==="12" && split_string[2]==="AM"){
        split_string[0] = "0"
        split_string.push(0)
    } else if(split_string[0]==="12" && split_string[2]==="PM"){
        split_string.push(0)
    } else if(split_string[2]=="PM"){
        split_string.push(720)
    } else if (split_string[2]==="AM"){
    split_string.push(0)
    }
    const minutes = (parseInt(split_string[0])*60)+parseInt(split_string[1])+split_string[3]
    return minutes
}

由于日期似乎无关紧要,您可以假设任何固定日期,将字符串转换为毫秒并进行比较

const lower = '8:00 AM'
const upper = '9:30 PM'
const time  = '12:24 PM'
const delta_lower = Date.parse(`1/1/1970 ${lower}`)
const delta_upper = Date.parse(`1/1/1970 ${upper}`)
const delta_time  = Date.parse(`1/1/1970 ${time}`)
console.log(delta_time > delta_lower && delta_time < delta_upper) //prints true
const lower='8:00am'
康斯特河上游='9:30 PM'
常数时间='12:24 PM'
const delta_lower=Date.parse(`1/1/1970${lower}`)
const delta_upper=Date.parse(`1/1/1970${upper}`)
const delta_time=Date.parse(`1/1/1970${time}`)
log(delta_time>delta_lower&&delta_time
由于日期似乎无关紧要,您可以假设任何固定日期,将字符串转换为毫秒,然后进行比较

const lower = '8:00 AM'
const upper = '9:30 PM'
const time  = '12:24 PM'
const delta_lower = Date.parse(`1/1/1970 ${lower}`)
const delta_upper = Date.parse(`1/1/1970 ${upper}`)
const delta_time  = Date.parse(`1/1/1970 ${time}`)
console.log(delta_time > delta_lower && delta_time < delta_upper) //prints true
const lower='8:00am'
康斯特河上游='9:30 PM'
常数时间='12:24 PM'
const delta_lower=Date.parse(`1/1/1970${lower}`)
const delta_upper=Date.parse(`1/1/1970${upper}`)
const delta_time=Date.parse(`1/1/1970${time}`)
log(delta_time>delta_lower&&delta_time
为什么不“9:00AM”->“0900”,这已经是一个相当成熟的惯例了。从来没有人说过“540点见”,意思是早上9点。“将时间转换为GMT”:这可能是一种误解。您是否在打印日期时没有调用
.toString
.toLocaleString
?@trincot我确实误解了。当我执行
console.log(Date(“12:42 AM”)
时,它实际上返回了当前日期,感谢您的澄清。另一个例子证明,最好将日期/时间值存储为适当的
Date
对象,而不是字符串。也许库会让您的生活更轻松。为什么不“9:00AM”->“0900”这已经是一个相当成熟的惯例。从来没有人说“540点见我”,意思是早上9点。“将时间转换为GMT”:这可能是一种误解。你是否可能在没有调用
.toString
.tolocalesting
?@trincot的情况下打印了日期?当我调用
控制台.log(日期(“12:42 AM”)时,我确实误解了
它实际上返回了当前日期,感谢您的澄清。另一个例子证明,最好将日期/时间值存储为适当的
date
对象,而不是字符串。也许库会让您的生活更轻松。