How to save a timezone correctly with Ruby and MongoId?
It looks like you need to specify the field type of your date attribute. I would use a Time field if you want mongoid to handle the zones properly.
class Lineup
include Mongoid::Document
field :date, type: Time
end
You will also probably want to set the following in config/mongoid.yml
defaults: &defaults
use_utc: false
use_activesupport_time_zone: true
This sounds counterintuitive, but this is the current way to make mongoid use UTC as the default timezone.
Finally, have a look at the mongoid-metastamp gem. It will give you much better support for querying across multiple timezones, while still seamlessly working like a native Time field.
Rails - How to save datetimes correctly in MongoID and trigger them with whenerver (cronjobs)?
Try the following
def self.activate_due
events_due = Event.where(
:eventStart.to_utc.lte =>(Time.now.to_utc),
:eventStart.to_utc.gte => (1.minute.ago.to_utc))
events_due.each do |e|
e.activate
end
end
Plesse note that this will work with UTC times, so if you have an event in UTC - 7 timezone don't think it will get activated now if the server timezone is UTC + 2
Is it possible to change default TimeZone in MongoDB using Rails 3?
You can change the timezone of your application so that ruby's date object will auto configure the dates. MongoDB will always store time in UTC.
MongoDB has no internal knowledge of timezones.
Query mongodb datetime output to be for certain timezone
Check out the documentation - datetime
objects returned by pymongo always represent a time in UTC, just as dates stored in MongoDB are always stored as (that is, assumed to be in) UTC
pymongo can convert your datetimes automatically to be time zone aware if you set the tz_info flag to True when creating your Connection. You can then use datetime.astimezone() method to convert to another time zone if you wish.
So for example you could use pytz for timezones or if you only need EST write your own:
import datetime
class Eastern(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hours=-5)
def tzname(self, dt):
return "EST"
def dst(self, dt):
return datetime.timedelta(0)
EST = Eastern()
Then you can do this:
# Get now for EST
now = datetime.datetime.now(EST)
print now.strftime('%Y-%m-%d %H:%M:%S')
from pymongo import Connection
# Create a timezone aware connection
connection = Connection('localhost', 27017, tz_aware=True)
# Save your data
db = connection.test_database
db.stackoverflow.save({"Type": "reports", "patId": 'JOHNSONGARY', "lastUpdated": now})
doc = db.stackoverflow.find()[0]
print doc['lastUpdated'].astimezone(EST).strftime('%Y-%m-%d %H:%M:%S')
# Confirm they are the same
assert doc['lastUpdated'].astimezone(EST).strftime('%Y-%m-%d %H:%M:%S') == now.strftime('%Y-%m-%d %H:%M:%S')
Set Timezone For User Before Create Rails
I think you are looking for callbacks, please reference the Ruby on Rails guide on Callbacks here.
In this case, you want to run your function only when the record is created, so you will use before_create
:
class User
before_create :set_created
include Mongoid::Document
include Mongoid::Paperclip
field :created, type: Time
field :time_zone, type: String
def set_created
self.created = Time.now.in_time_zone(self.time_zone)
end
end
Please note the before_create at the top of the class.
Mongoid date range query
There was a bug in Mongoid. Fixed now.
For more information:
https://github.com/mongoid/mongoid/issues/761
https://github.com/mongoid/mongoid/commit/f326de5acc969e1342e640dc026de7e94bf4cf49#lib/mongoid/matchers.rb
Querying for last 7 or 30 days date range with mongodb mongoid rails
This has finally been resolved. I needed to stored the date in a variable and then query it this way:
Person.first.person_email_clicks.gt(date: u).lt(date: e).
or query it this way:
Person.first.person_email_clicks.where({:date.gt => u, :date.lt => e})
This is the full step to get the desired results:
u = Person.first.person_email_clicks.first.date
=> Wed, 22 Apr 2015 22:12:00 +0000
e = Person.first.person_email_clicks.last.date
=> Sat, 25 Apr 2015 22:12:00 +0000
h = Person.first.person_email_clicks.gt(date: u).lt(date: e).to_a
Which returned 2 records as shown below:
=> [
#<PersonEmailClick _id: 55381d536461760b6c010000, name: "seller", date: 2015-04-23 01:12:00 UTC, daily_total: 0, email_open: 0, page_views: 0, clicks: 0, visits: 0>,
#<PersonEmailClick _id: 55381d916461760b6c020000, name: "giver", date: 2015-04-24 22:12:00 UTC, daily_total: 0, email_open: 0, page_views: 0, clicks: 0, visits: 0>
]
Related Topics
Conditional Haml - If Else Nesting
Testing Simple Sti with Factorygirl
Convert a Partial to Method/Block for Speed
Elegantly Selecting Attributes from Has_Many :Through Join Models in Rails
Changing Value of Ruby Variables/References
Using Acts_As_List with Has_Many :Through in Rails
How to Integrate Rubocop with Rake
Why Doesn't "Case" with "When > 2" Work
Differencebetween 'File.Read' and 'Io.Read'
How to Calculate 32 Bit Crc in Ruby on Rails
How to Remove a Non-Breaking Space in Ruby
Why Is "❨╯°□°❩╯︵┻━┻" with Such an Encoding Used for a Method Name
Ruby: How to Calculate a Path Relative to Another One