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

前端 未结 4 1306
被撕碎了的回忆
被撕碎了的回忆 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 15:54

    Here's another option:

    Time.at(Date.today.to_datetime.to_i).utc
    

    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 a Time instance, it can be serialized to BSON without any problem, as Time is a supported primitive type, that is to say, it can be saved using MongoMapper to the database.

    0 讨论(0)
  • 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
    => #<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
    

    Good luck.

    ===

    And by using

    Date.to_mongo(start_date) 
    

    it works for me.

    0 讨论(0)
  • 2021-01-14 16:12

    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:

    DateTime.now.new_offset(0)
    
    0 讨论(0)
  • 2021-01-14 16:16

    As per EfratBlaier's comment I have updated the answer.

    Date.today.to_time.utc

    0 讨论(0)
提交回复
热议问题