如何在MongoMapper& Ruby / Rails? [英] How to convert Date into UTC in MongoMapper & Ruby/Rails?
问题描述
我添加了这行代码
self.auth_history.push [start_date, self.coupon_code]
并收到此错误消息
Date is not currently supported; use a UTC Time instance instead.
我也尝试过 start_date.utc
它也没有工作。
I also tried start_date.utc
, but it didn't work either.
请帮忙。谢谢。
推荐答案
我得到了西雅图旅团队的答案 -
I got this answer from Seattle Brigade group -
===
我没有看到你的代码中定义的start_date是MongoMapper中的一个关键字,所以
我假设你正在创建自己的日期对象,直接通过Ruby,
或由Rails包装。据我所知,有人请更正我,Mongo
以UTC为单位,以UTC为单位存储日期。所以当你在MongoMapper中定义一个
键时,你可以在
Ruby中包含一个Time对象。
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.
因此,如果你想在Mongo中存储一个日期,而不是由MongoMapper创建的
,请确保在UTC中创建一个Time对象。
MongoMapper附带一个名为to_mongo的Date mixin方法,您可以使用它。
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.
>> Time.now.utc
=> Fri Jan 28 03:47:50 UTC 2011
>> require 'date'
=> true
>> date = Date.today
=> #<Date: 4911179/2,0,2299161>
>> Time.utc(date.year, date.month, date.day)
=> Thu Jan 27 00:00:00 UTC 2011
>> require 'rubygems'
=> true
>> require 'mongo_mapper'
=> true
>> Date.to_mongo(date)
=> Thu Jan 27 00:00:00 UTC 2011
但请注意时间的变化。 >
But watch out for the time change.
>> Date.to_mongo(Time.now)
=> Thu Jan 27 00:00:00 UTC 2011
>> Date.to_mongo(Time.now.utc)
=> Fri Jan 28 00:00:00 UTC 2011
祝你好运。
===
并使用
Date.to_mongo(start_date)
它适用于我。
这篇关于如何在MongoMapper& Ruby / Rails?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!