• 请不要在回答技术问题时复制粘贴 AI 生成的内容
BlackFri
V2EX  ›  程序员

MongoDB 时间戳和当前时间比较

  •  
  •   BlackFri · Dec 2, 2021 · 2183 views
    This topic created in 1647 days ago, the information mentioned may be changed or developed.
    需求:用户在前端使用 DatePicker 选定一个时间,返回给后端,并存储到 MongoDB 里(假设这个字段是 startTime ),在之后的请求操作中需要判断 startTime 与 Date.now() 的差值是否小于 30 * 60 * 1000 (也就是 30 min )

    问题:MongoDB 存储的时间是不带时区的,Date.now() 可以正确返回当前时间(比如北京时间),有时区,这个时候就很难比较了

    求求大佬们了
    8 replies    2021-12-03 18:10:01 +08:00
    ThisDay
        1
    ThisDay  
       Dec 2, 2021
    都转成时间戳或者都转成 utc 时间不就行了,没明白你什么意思
    AngryPanda
        2
    AngryPanda  
       Dec 2, 2021 via iPhone
    难度在哪里🧐
    cluulzz
        4
    cluulzz  
       Dec 2, 2021 via iPhone
    mongodb 聚合有个$function
    unco020511
        5
    unco020511  
       Dec 3, 2021
    你想怎么存就怎么存啊,楼上不是说了,存时间戳或者 UTC 时间
    gadfly3173
        6
    gadfly3173  
       Dec 3, 2021
    @BlackFri #3 从你这个链接里点进 Date 的说明可以看到:BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future. 所以它存的就是时间戳吧。。。
    leopod1995
        7
    leopod1995  
       Dec 3, 2021
    Date.now 返回的也是时间戳, db 也是时间戳
    BlackFri
        8
    BlackFri  
    OP
       Dec 3, 2021
    @leopod1995

    db 是 ISO 时间戳

    const diff =
    new Date(startTime).getTime() -
    new Date(new Date().toISOString()).getTime();

    const diffMinutes = Math.abs(diff / 1000 / 60);

    if (diff > 30) {
    doSomething()
    }

    已解决,感谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2819 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 13:22 · PVG 21:22 · LAX 06:22 · JFK 09:22
    ♥ Do have faith in what you're doing.