如何在MongoMapper和Ruby/Rails中将Date转换为UTC?

Mei*_*Mei 3 ruby-on-rails date utc mongodb

我添加了这行代码

self.auth_history.push [start_date, self.coupon_code]
Run Code Online (Sandbox Code Playgroud)

并得到此错误消息

Date is not currently supported; use a UTC Time instance instead.
Run Code Online (Sandbox Code Playgroud)

我也试过了start_date.utc,但它也没用.

请帮忙.谢谢.

Mei*_*Mei 8

我从西雅图旅团得到了这个答案 -

===

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.

>> 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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Good luck.

===

And by using

Date.to_mongo(start_date) 
Run Code Online (Sandbox Code Playgroud)

it works for me.