如何在 MongoMapper 中将日期转换为 UTC红宝石/导轨?
我添加了这行代码
self.auth_history.push [start_date, self.coupon_code]
并收到此错误消息
Date is not currently supported; use a UTC Time instance instead.
我也尝试了 start_date.utc
,但它也不起作用。
请帮忙。谢谢。
I added this line of code
self.auth_history.push [start_date, self.coupon_code]
And got this error message
Date is not currently supported; use a UTC Time instance instead.
I also tried start_date.utc
, but it didn't work either.
Please help. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我从西雅图旅组得到了这个答案 -
===
我没有看到你的代码中定义的 start_date 作为 MongoMapper 中的键,所以
我假设您正在创建自己的日期对象,或者直接通过 Ruby,
或由 Rails 包裹。据我所知,请有人纠正我,Mongo
将日期存储为 UTC 时间(自纪元以来的毫秒数)。所以当你定义一个
在 MongoMapper 中使用 :date 映射键,您将 Time 对象包装在
红宝石。
因此,如果你想在 Mongo 中存储日期,但事实并非如此
由 MongoMapper 创建,请确保您创建 UTC 时间对象。
MongoMapper 附带了一个名为 to_mongo 的 Date mixin 方法,您可以使用它。
但要注意时间变化。
祝你好运。
===
通过使用
它对我有用。
I got this answer from Seattle Brigade group -
===
I didn't see start_date defined in your code as a key in MongoMapper, so
I'll assume you're creating your own date object, either directly via Ruby,
or wrapped by Rails. As far as I know, and someone please correct me, Mongo
stores dates as UTC time in milliseconds since epoch. So when you define a
key with a :date mapping in MongoMapper, you're wrapping a Time object in
Ruby.
Therefore, if you want to store a date inside of Mongo, and it wasn't
created by MongoMapper, make sure you create a Time object in UTC.
MongoMapper comes with a Date mixin method called to_mongo that you can use.
But watch out for the time change.
Good luck.
===
And by using
it works for me.
首先,我认为问题标题的描述不好。实际上,不同时区之间的差异在于时间而不是日期。所以,说我想将日期转换为 UTC 格式确实不合适。
这是 Ruby 中将 DateTime 转换为其 UTC 格式的另一种方法:
First, I think the question title is bad in description. Actually, the difference between different timezone is on Time not on Date. So, it's really not proper to say I want to convert a date to UTC format.
Here is another way in Ruby to convert DateTime to its UTC format:
这是另一个选项:
这里我使用
Date.today
作为任意示例日期。替换为您要转换的任何日期。一旦日期转换为Time
实例,它就可以毫无问题地序列化为BSON
,因为Time
是受支持的原始类型,即也就是说可以使用MongoMapper保存到数据库中。Here's another option:
Here I am using
Date.today
as an arbitrary example date. Replace with whatever date you want to convert. Once the date is converted to aTime
instance, it can be serialized toBSON
without any problem, asTime
is a supported primitive type, that is to say, it can be saved using MongoMapper to the database.根据 EfratBlaier 的评论,我更新了答案。
日期.今天.to_time.utc
As per EfratBlaier's comment I have updated the answer.
Date.today.to_time.utc