Lets say I want to compare the dates only of two datetime columns within 1 record. So I don't want the time looked at.
I.e.
viewed_date, and updated_at (I added viewed_date) are two datetime formats, but I only want to see if they occurred on the same day or days apart. The problem with datetime is that its comparing the times, which is just too specific for me right now.
Thanks
-Elliot
Declare a new attribute that contains just the date:
class WhateverModel < ActiveRecord::Base
...
def viewed_date_only
viewed_date.to_date
end
end
Use that for your comparison in the controller or wherever.
You can compare only date of object without comparing time like this:-
start_date :-"2015-04-06 15:31:43 +0530"
end_date :- "2015-04-16 15:31:43 +0530 "
post_review.all.where("(created_at::date >= :start_date) AND
(created_at::date <= :end_date)", start_date: start_date.strftime("%Y-%m-%d"),end_date: end_date.strftime("%Y-%m-%d"))
Above query gets all the records made between 6 to 16 April
Related
Using Rails 6.
I have an ElectricityUsage model, with a Date field, date. I want to extract all the values for amount only for the current month. How would I accomplish this?
What I immediately attempted was the following:
ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat).where(date.month: Date.today.month)
But that obviously doesn't work, and it wouldn't even account for the year, either. My DB is running on PostgreSQL, if that makes a difference.
You can use where with Date.current.all_month, which basically is just translated into a query using BETWEEN where the start date is the first day of the month and end date is the last one:
ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat, date: Date.current.all_month)
This should work for you
ElectricityUsage.where(habitat: current_user.reservations[0].room.habitat).where("EXTRACT(MONTH FROM date) = ?", Date.current.month)
PostgreSQL Date/Time Functions and Operators
Might be a delayed response but you can use date_queries gem
model ElectricityUsage < ActiveRecord::Base
date_queries_for :date
end
Then you can simply use ElectricityUsage.dates_in_this_month to find all the records that false in current month
I'm working on an event system where admins can select events to feature and add promotional text. As they need to add additional text the featured events are in their own table and reference the event details.
I'm now trying to output featured events for each day in the next week. Simplified example:
day = DateTime.now.to_date
featured_events = #featured_events.where('event.start_datetime = ?', day)
The problem is that start_datetime is in datetime format and day is in date format so it always outputs nothing. Is it possible to compare these two values with .where()?
Thanks!
May be you're looking for this:
#featured_events.where('event.start_datetime > ? and event.start_datetime < ?', DateTime.now, 1.day.from_now.beginning_of_day)
You don't say what database you're using.
In PostgreSQL we'd truncate the datetime inside the DB query so the DBM can do the compare. On MySQL we'd use a function to convert the datetime to a date.
I have a class that has two params: start_date and end_date.
Those are formatted like - 2012-07-12 and 2012-07-24.
I was to subtract end_date from start_date.
Previous Googling has left me high and dry. Should I convert these to something else to do subtraction?
Convert them into dates and subtract them:
require 'date'
start_date = Date.parse('2012-07-12')
end_date = Date.parse('2012-07-24')
(start_date - end_date).to_i
=> -12
If you want the number of days (end_date-start_date).days should work fine. You'll probably get a Rational number of days, in which case you can just use to_i
If i am not miskaten, the params come in form of a String, so you have to convert it to a Date, DateTime, or Time to do math operations with them.
You can refer to this question to more details.
How can I find the number of days between two Date objects in Ruby?
You can just substract two DateTime objects
Using 1.9
require 'date'
DateTime.parse(end_date) - DateTime.parse(start_date)
I'm trying to execute a query in rails 3 with the following syntax: CourseOrder.where("DATE(ordered_at) = ?", date).
My problem is that rails saves all times in UTC, so in my Timezone (+2) at 0:33 its the 4th but in UTC its the 3th of the month. Is there a way to query the date part of a DateTime with Timezone?
Don't use date, do it like this instead:
time = DateTime.civil_from_format(:local, 2011, 4, 9)
CourseOrder.where("ordered_at > ? AND ordered_at < ?", time - 1.day, time)
You're storing a datetime, so query that instead of trying to use date, which doesn't account for Timezones.
solved the problem with a change in which values I compare.
I have a Date value to, and now I'm comparing a date value with a date value which is better than comparing date value with datetime value which have to fail.
thanks for leading me to the right direction
FYI, There is some overlap in the initial description of this question with a question I asked yesterday, but the question is different.
My app has users who have seasonal products. When a user selects a product, we allow him to also select the product's season. We accomplish this by letting him select a start date and an end date for each product.
We're using date_select to generate two sets of drop-downs: one for the start date and one for the end date.
Including years doesn't make sense for our model. So we're using the option: discard_year => true
When you use discard_year => true, Rails sets a year in the database, it just doesn't appear in the views. Rails sets all the years to either 0001 or 0002 in our app. Yes, we could make it 2009 and 2010 or any other pair. But the point is that we want the months and days to function independent of a particular year. If we used 2009 and 2010, then those dates would be wrong next year because we don't expect these records to be updated every year.
My problem is that we need to dynamically evaluate the availability of products based on their relationship to the current month. For example, assume it's March 15. Regardless of the year, I need a method that can tell me that a product available from October to January is not available right now.
If we were using actual years, this would be pretty easy.
For example, in the products model, I can do this:
def is_available?
(season_start.past? && season_end.future?)
end
I can also evaluate a start_date and an end_date against current_date
However, in setup I've described above where we have arbitrary years that only make sense relative to each other, these methods don't work. For example, is_available? would return false for all my products because their end date is in the year 0001 or 0002.
What I need is a method just like the ones I used as examples above, except that they evaluate against current_month instead of current_date, and past? and future months instead of years.
I have no idea how to do this or whether Rails has any built in functionality that could help. I've gone through all the date and time methods/helpers in the API docs, but I'm not seeing anything equivalent to what I'm describing.
Thanks.
Set the year of the current date to 1000 and perform a range compare with the start and end dates.
def is_available?
t = Date.today
d = Date.new(1000, t.month, t.day)
(season_start..season_end).include?(d) or
(season_start..season_end).include?(d+1.year)
end
Second comparison above is to address the following scenario:
Lets say today Jan 15 and the season is from Oct - Feb. In our logic, we set the date to Jan 15 1000. This date will not be within Oct 1 1000 - Mar 1 1001. Hence we do the second comparison where we advance the date by a year to Jan 15 1001, which is within the range.
You might want to consider not using Date objects. What if season_start_month and season_end_month were each an integer 1-12, set with your dropdown? Then when doing your is_available? comparison, you could dynamically create the full date for season_start, doing some math for transitions over December to January. This could use some refactoring, and isn't tested, but should do the trick. Assumes that season_start_month and season_end_month are integers stored in this model:
class Product < ActiveRecord::Base
def is_available?
now = Time.now
season_start < now && now < season_end
end
def season_start
now = Time.now
current_month = now.month
season_start_year = season_start_month < current_month ? now.year : now.year - 1
Time.local(season_start_year, season_start_month)
end
def season_end
now = Time.now
current_month = now.month
season_end_year = season_end_month > current_month ? now.year : now.year + 1
Time.local(season_end_year, season_end_month)
end
end