V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
BlackFri
V2EX  ›  程序员

MongoDB 时间戳和当前时间比较

  •  
  •   BlackFri · 2021-12-02 16:01:31 +08:00 · 1493 次点击
    这是一个创建于 847 天前的主题,其中的信息可能已经有所发展或是发生改变。
    需求:用户在前端使用 DatePicker 选定一个时间,返回给后端,并存储到 MongoDB 里(假设这个字段是 startTime ),在之后的请求操作中需要判断 startTime 与 Date.now() 的差值是否小于 30 * 60 * 1000 (也就是 30 min )

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

    求求大佬们了
    8 条回复    2021-12-03 18:10:01 +08:00
    leeyuzhe
        1
    leeyuzhe  
       2021-12-02 16:08:55 +08:00
    都转成时间戳或者都转成 utc 时间不就行了,没明白你什么意思
    AngryPanda
        2
    AngryPanda  
       2021-12-02 17:21:06 +08:00 via iPhone
    难度在哪里🧐
    cluulzz
        4
    cluulzz  
       2021-12-02 22:29:00 +08:00 via iPhone
    mongodb 聚合有个$function
    unco020511
        5
    unco020511  
       2021-12-03 09:51:30 +08:00
    你想怎么存就怎么存啊,楼上不是说了,存时间戳或者 UTC 时间
    gadfly3173
        6
    gadfly3173  
       2021-12-03 11:21:05 +08:00
    @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  
       2021-12-03 14:42:59 +08:00
    Date.now 返回的也是时间戳, db 也是时间戳
    BlackFri
        8
    BlackFri  
    OP
       2021-12-03 18:10:01 +08:00
    @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()
    }

    已解决,感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2731 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 15:30 · PVG 23:30 · LAX 08:30 · JFK 11:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.