MongoDB 时间戳和当前时间比较

2021-12-02 16:01:31 +08:00
 BlackFri
需求:用户在前端使用 DatePicker 选定一个时间,返回给后端,并存储到 MongoDB 里(假设这个字段是 startTime ),在之后的请求操作中需要判断 startTime 与 Date.now() 的差值是否小于 30 * 60 * 1000 (也就是 30 min )

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

求求大佬们了
1523 次点击
所在节点    程序员
8 条回复
leeyuzhe
2021-12-02 16:08:55 +08:00
都转成时间戳或者都转成 utc 时间不就行了,没明白你什么意思
AngryPanda
2021-12-02 17:21:06 +08:00
难度在哪里🧐
BlackFri
2021-12-02 18:38:39 +08:00
cluulzz
2021-12-02 22:29:00 +08:00
mongodb 聚合有个$function
unco020511
2021-12-03 09:51:30 +08:00
你想怎么存就怎么存啊,楼上不是说了,存时间戳或者 UTC 时间
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
2021-12-03 14:42:59 +08:00
Date.now 返回的也是时间戳, db 也是时间戳
BlackFri
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()
}

已解决,感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/819567

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX