How can I query for records between 12:45:00 and 12:45:59 in Rails?
The dateTime for my record is Mon, 06 Nov 2022 12:12:10.000000000 EST -05:00 but when I run find_by("datetime_field::time BETWEEN '12:12:00' AND '12:13:00'"), it returns nil.
Datebase: PostgresQL
This is likely a time zone issue. If you are doing things in the "normal" Rails way, your column is probably of type timestamp without time zone and the timestamps are stored in UTC. You could run this to see what the times are:
YourModel.select("datetime_field::time as time").map(&:time)
You will probably see an array of UTC times, and your find_by will work correctly if you use UTC times instead of EST times.
Related
I'm trying to get the time until 12:00 AM in the users timezone. How can I do this in rails?
I want to get the time until 12:00 AM and then add that time to the current time in rails to store it in the database because I want to have a field with the GMT time at is the equivalent to 12:00 AM in the users timezone
I'm using this gem:
gem 'time_difference', '~> 0.5.0'
In order to get the time difference between two timestamps
TimeDifference.between(DateTime.now, created_at)
But I'm not sure how to get the time until 12:00 AM in the users timezone.
Thanks
Given a particular timezone, you can use Rails' tools for dealing with timezones to just directly find out when midnight is for a particular timezone. This example supposes you have a time_zone column on your User model with an appropriate value (e.g., America/Chicago, or anything else Rails supports):
midnight_for_user = ActiveSupport::TimeZone[user.time_zone].now.midnight.tomorrow
For example, I can use the same logic to find when midnight is for a person in New York:
pry(main)> Time.current
=> Thu, 05 Jan 2017 10:34:02 CST -06:00
pry(main)> ActiveSupport::TimeZone['America/New_York'].now.midnight.tomorrow
=> Fri, 06 Jan 2017 00:00:00 EST -05:00
Note that I'm looking for midnight tomorrow; remember that "midnight" for a given day is actually the very first minute of the day, not the last.
I'm having a frustrating issue that I can't seem to narrow down. I have searched many similar articles but they are not close enough to my issue to resolve. I am trying to pull a time from the database and display it in more than one time zone. My Rails app is using UTC as default. Here is what I'm doing:
On the create action I take the string of time which will be saved in the time column in my DB:
params[:schedule][:start] = "09:00"
Time.zone = "Central Time (US & Canada)"
#schedule.start = Time.zone.parse(params[:schedule][:start])
The above formats the time as it is supposed to:
2016-04-12 09:00:00 -0500
This is saved in the DB as:
2000-01-01 14:00:00
This has no time offset which is fine since I know it's in UTC. The problem happens when I go to display the time:
#schedule.start.in_time_zone("Central Time (US & Canada)")
This returns:
Sat, 01 Jan 2000 08:00:00 CST -06:00
Now, since this is a time column, I don't care about the date. I plan on formatting the value to only show the time. However, it is showing CST when it is currently CDT.
I can't figure out why this is happening. As I said I am not setting the Time Zone anywhere in my application.rb or anywhere else and I only set the Time zone on the create action which should be fine when moving to a new action.
Any help on clarifying this would be awesome!
This seems to be because when the time is stored it is stored with the date in the year 2000-01-01 which seems to be why it is using CST. How can I ignore the date when converting it to a particular timezone or will I need to change the column type to DateTime to get this to work properly?
It is showing CST simply because the time is read from the database including the stored date, i.e. it's read as 09:00 of Jan 1st 2000.
I guess you'd have to parse the time upon reading the attribute back. You can use a helper method in your model, for example:
# schedule model
def start_in_zone(zone)
self.start.strftime("%H:%M").in_time_zone(zone)
end
This will take only the hours and minutes part of the stored time and parse it in the given time zone with the date set to today. See this example:
"Sat, 01 Jan 2000 08:00:00".to_time.
strftime("%H:%M").
in_time_zone("Central Time (US & Canada)")
# => Tue, 12 Apr 2016 08:00:00 CDT -05:00
The fact that it matters whether it's CST or CDT means you do, on some level, care about the date. While I'm not familiar with the exact rules of Daylight Savings in that region, I do know that Jan 1 is the middle of winter and will definitely not be on Daylight Savings time.
Add the relevant date into your #schedule before putting it into a time zone, and it should fix the problem.
I want to orders which are confirmed particular day.
This is particular day:
today = Time.zone.now
Wed, 10 Jun 2015 13:31:16 IST +05:30
This is range of particular day
value = today.beginning_of_day()..today.end_of_day()
Wed, 10 Jun 2015 00:00:00 IST +05:30..Wed, 10 Jun 2015 23:59:59 IST +05:30
But when I execute this, SQL query date range is changed,
orders = Order.where(confirmed_at: value)
SELECT "orders".* FROM "orders" WHERE "orders"."confirmed_at" BETWEEN '2015-06-09 18:30:00.000000' AND '2015-06-10 18:29:59.999999' ORDER BY orders.confirmed_at DESC
In this orders confiremed between '2015-06-09 18:30:00.000000' AND '2015-06-10 18:29:59.999999'
But I wants confirmed between 'Wed, 10 Jun 2015 00:00:00 IST +05:30..Wed, 10 Jun 2015 23:59:59 IST +05:30'
You can use Time.zone.now.to_time for today.
today = Time.zone.now.to_time
value = today.beginning_of_day()..today.end_of_day()
I hope this helps.
Which DB are you using?
ActiveRecord will declare time columns using data types that do not support timezones. For example, in Postgres it will use timestamp without time zone.
This means that all Time, DateTime and TimeWithZone values set on an ActiveRecord object will be written to the DB as UTC.
Rails will then take care to apply and remove the right offsets each time the values are read or written, using the current value of Time.zone (e.g. for the current web request).
Just check the docs for TimeWithZone and think about what should go in your WHERE clause.
It probably depends on the specific context, but you might have to use UTC values in your query.
Rails 4.2 and PostgreSQL 9.4.
I have events with starts_at and time_zone columns.
I'd like a SQL query to return all events that start, in their local time zone, on a specified date.
I.e. if an event starts at 11pm in Hawaii on Jan 24th:
t1 = ActiveSupport::TimeZone['Hawaii'].parse("2015-01-24 23:00:00")
=> Sat, 24 Jan 2015 23:00:00 HST -10:00
t1.in_time_zone('UTC')
=> Sun, 25 Jan 2015 09:00:00 UTC +00:00
And if an event starts at 1am in Hong Kong on Jan 24th:
t2 = ActiveSupport::TimeZone['Hong Kong'].parse("2015-01-24 01:00:00")
=> Sat, 24 Jan 2015 01:00:00 HKT +08:00
t2.in_time_zone('UTC')
=> Fri, 23 Jan 2015 17:00:00 UTC +00:00
The events occur on the 25th and 23rd of Jan in Rails' implicit UTC database zone, but both events occur on the 24th in their own time zone.
I'd like to write a SQL query akin to:
SELECT * FROM events WHERE (events.starts_at at time zone 'UTC' at time zone events.time_zone)::date = '2015-01-24';
(The initial conversion to UTC is required for a timestamp I believe)
However I get an error ERROR: time zone "Hawaii" not recognized
This is because PostgreSQL time zone names do not match with that of Rails (SELECT * FROM pg_timezone_names; for a list.)
Is there an alternative method where I can still do the query in SQL but not have this problem? I don't want to load the entire events set into Rails and process it there as it is very large and this is a frequent query.
As a small context as to why I need this query: I have a membership pass valid over a certain date range which gives you access to events which can occur in different time zones.
If there is no other way to do this, is there any tool that converts between the Rails names for time zones and that used by PostgreSQL so that I can save both the Rails zone and the PostgreSQL zone in the database record?
Using time zone abbreviations such as PDT instead (I don't even know if these are consistent between Rails and PostgreSQL either) doesn't deal with daylight savings time (which, granted, may not be an issue here but is not satisfactory).
My app is working in "Moscow" (+04:00) timezone. But sometimes I need to create time object by only local time (for example "01 may 2012 13:45") and name of ActiveSupport::TimeZone object (for example "Berlin": +02:00 in Summer Time and +01:00 otherwise).
For example if I get "01 may 2012 13:45" and "Berlin" as input I want to yield "2012-05-01 13:45:00 +0200" or "2012-05-01 11:45:00 +0000". I create following function:
def from_local_datetime(local_datetime, time_zone)
offset = Time.now.in_time_zone(time_zone).formatted_offset
datetime = case local_datetime
when String
DateTime.parse(local_datetime)
else
DateTime.new(local_datetime)
end.change(:offset => offset)
return datetime
end
And at the first look it works as I expected. But is it a best practice for this kind of task? May be in some situation It works with errors. I'm not definitely sure.
I would be greatful to any comments.
UPD: I think bug may occur about time when DST changing the time. For example 26 march 2011 was GMT+1 in Berlin time zone and Time.now.in_time_zone("Berlin").formatted_offset returns "GMT+1", but it would be GMT+2 in 27 march 2011. So if I call from_local_datetime("28 march 2011", "Berlin") before 27 march it returns 28 march 2011 00:00:00 +0100, but If I call it after changing the time my function returns 28 march 2011 00:00:00 +0200 :(
Your conversion method is the right approach.
With web sites, you should make sure times are stored as UTC in the database. If you can get the UTC value out of the database, instead of the local time (or maybe you can set your web server's time zone to UTC) it won't have to convert the time from UTC to local time, when you are going to then convert it to the user's timezone anyway.
And, of course, you will have to store the user's time zone preference.
TZInfo::Timezone.get('Europe/London')
Find the time zone
http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html