How to convert Date into UTC in MongoMapper & Ruby/Rails?

前端 未结 4 1323
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 15:24

I added this line of code

self.auth_history.push [start_date, self.coupon_code]

And got this error message

Date is not cu         


        
4条回答
  •  独厮守ぢ
    2021-01-14 16:02

    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.

    >> Time.now.utc
    => Fri Jan 28 03:47:50 UTC 2011
    >> require 'date'
    => true
    >> date = Date.today
    => #
    >> 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
    

    Good luck.

    ===

    And by using

    Date.to_mongo(start_date) 
    

    it works for me.

提交回复
热议问题