如何在 Meteor 中存储日期和时间以进行范围查询? [英] How to store Date and Time in Meteor for range queries?
问题描述
我的应用程序需要创建在浏览器中以 3 个不同时区显示 startDate 的对象.日期还必须包括确切的时间.日期应该以这样一种方式存储,它允许查询给我所有的 X 和 Y 之间的日期"并将其解析为 3 个时区.
My app needs to create objects that will have a startDate shown in 3 different timezones in browser. The date must also include the exact time. The date should be stored in such a way that it allows for queries "give me all for date between X and Y" and parse it to 3 timezones.
我的问题是我应该如何最好地保存(并随后检索)日期和时间,以便以后可以在日期范围内查询它,我是否应该使用 moment.js?我想到的是,将日期和时间保存在数据库中的单个 unix 时间戳中,并且在读取它时只需将其解析为具有该特定时区的日期和时间.这种方法是否正确,还是应该将其另存为纯 JavaScript 日期?mongoDB 可以查询 unix 时间戳作为日期范围还是需要普通的 Date 对象?
My question is how should I best save (and subsequently retrieve) the date and time so that I can query it later in date ranges, should I maybe use moment.js? What I thought of, is saving the date AND time both in a single unix timestamp in the database, and when reading it just parse it into the date and time with that specific timezone. Is this approach correct, or should I save it as plain javascript Date? Can mongoDB query unix timestamps as date ranges or does it need plain Date objects?
谢谢.
推荐答案
你需要知道的一切都可以在 此处.亮点:
Everything you need to know about this can be found here. The highlights:
将日期存储为 JavaScript
Date
对象.它们具有整数时间戳的所有查询优势,但您无需将它们转换回Date
对象即可使用它们.
Store dates as JavaScript
Date
objects. They have all the query advantages of integer timestamps, but you don't need to convert them back toDate
objects to use them.
范围查询的工作原理如下:Posts.find({creation_date: {$gte: startDate, $lt: endDate}})
Range queries work like so: Posts.find({creation_date: {$gte: startDate, $lt: endDate}})
您应该让服务器执行插入操作或使用 timesync 包来防止时钟偏差问题.
You should either have the server do the inserts or use the timesync package to prevent clock skew problems.
您可以使用 moment-timezone 将日期格式化为不同的时区.例如moment(date).tz("America/New_York").format('l LT')
You can use moment-timezone to format you dates to different timezones. e.g. moment(date).tz("America/New_York").format('l LT')
这篇关于如何在 Meteor 中存储日期和时间以进行范围查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!