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

MongoDB 时间戳和当前时间比较

  •  
  •   BlackFri · Dec 2, 2021 · 2582 views
    This topic created in 1821 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
    ThisDay
    Dec 2, 2021
    1
    都转成时间戳或者都转成 utc 时间不就行了,没明白你什么意思
    AngryPanda
    AngryPanda
    Dec 2, 2021 via iPhone
    2
    难度在哪里🧐
    cluulzz
    cluulzz
    Dec 2, 2021 via iPhone
    4
    mongodb 聚合有个$function
    unco020511
    unco020511
    Dec 3, 2021
    5
    你想怎么存就怎么存啊,楼上不是说了,存时间戳或者 UTC 时间
    gadfly3173
    gadfly3173
    Dec 3, 2021
    6
    @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
    leopod1995
    Dec 3, 2021
    7
    Date.now 返回的也是时间戳, db 也是时间戳
    BlackFri
    BlackFri
    OP
    Dec 3, 2021
    8
    @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   ·   Privacy   ·   Solana   ·   2221 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 13:39 · PVG 21:39 · LAX 05:39 · JFK 08:39
    ♥ Do have faith in what you're doing.