How to combine date and time? - ruby-on-rails-3

I am creating a Rails 3.2 app and I am not sure how to handle date and time.
Right now I have a field in the database called start_date which is a datetime timestamp and I also have a field called start_time.
I am using the fullcalendar plugin and for that to work I have to combine the start_date and start_time. How can I do this? (Not all events in the DB have a start_time).
Thankful for all input!

Ruby has the DateTime class, which essentially merges date and time together into one object. I would suggest making a migration that creates a new field that is called start and then combining your existing start_date and start_time fields into one:
def up
add_column :events, :start, :datetime
Event.find_each do |e|
d = e.start_date
t = e.start_time
e.start = DateTime.new(d.year, d.month, d.day, t.hour, t.min, t.sec)
end
remove_column :events, :start_date
remove_column :events, :start_time
end
def down
add_column :events, :start_date, :datetime
add_column :events, :start_time, :datetime
Event.find_each do |e|
s = e.start
e.start_date = s.to_date
e.start_time = s.to_time
end
remove_column :events, :start
end
If you need to get the date or time components in the future, you can use to_date or to_time, and the combined DateTime should work well with fullcalendar.

Related

Retrieve records between hours

I have the following model (I'm using ruby on rails) :
# MealSetting model
# week_day:integer
# pick_up_start_time:datetime
# pick_up_end_time:datetime
I want to retrieve all the meals that are available in a certain time, a meal is available if the pick_up_start_time <= current_hour and
pick_up_end_time >= current_hour.
pick_up_start_time:datetime and pick_up_end_time:datetime are actually dates but I'm only using the hours.
I have this query,
MealSetting
.where('pick_up_start_time::time <= ? and pick_up_end_time::time >= ?',
Time.now.utc.strftime("%T"),
Time.now.utc.strftime("%T"))
But it doesn't work because the dates in the database are stored in utc.
You can just use plain SQL and use the now() method.
Since you want to compare the hours inside the dates you can use the date_part function of postgres.
MealSetting.where("date_part('hour', NOW()) BETWEEN date_part('hour', pick_up_start_time) AND date_part('hour', pick_up_end_time)")
I think this is a perfect use case for scopes
class MealSettings < ApplicationRecord
scope :ready_for_pickup, -> { where("hour(pick_up_start_time) <= ?", Time.now.utc.hour) }
scope :before_pickup_ends, -> { where("hour(pick_up_end_time) >= ?", Time.now.utc.hour) }
end
MealSettings.ready_for_pickup.before_pickup_ends

how to write Rails model query between date

This is my sql query I wont to convert into rails model query
sql : SELECT "vouchers".* FROM "vouchers" WHERE "vouchers"."business_id" = 31 AND '2014-08-20' between start_date and end_date;
My tried model query but this not working please help me to make it working
Voucher.where(["#{Date.today} BETWEEN ? AND ?",:start_date,:end_date])
Try in this format:
data = ModelName.where("today >= from_date AND today <= to_date")
Assuming that start_date and end_date are columns try this version
Voucher.where("current_date between start_date and end_date").where(business_id: 31)
Model.where("DATE(created_at) > :today AND DATE(promoted_till_date) < :two_weeks", today: Date.today, two_weeks: Date.today+14.days)

How to compare current date to given date in MySQL

How to compare current date to given date in MySQL I am using like that code but it's not working.
<%
rs=st.executeQuery("select approcode,approemail,appromon,approvemon,approtue,approvetue,approwed,approvewed,approthr,approvethr,approfri,approvefri,approsat,approvesat,commen,months,SUM(nol) from `pushkalit`.`approval`WHERE (CONVERT( `approcode` USING utf8 ) LIKE '%"+user+"%') AND appromon=DATE(now()) OR approtue=DATE(now()) OR approwed=DATE(now()) ");
// i have given in mysql, appromon varchar(30).....so on dateformat have dd/MM/yyyy
%>
You can compare it like
DATE(NOW()) = DATE(duedate)
Will compare only the date part.
you should try this to simple code asL:
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())
See DATE_FORMAT()
SELECT
approcode, approemail, appromon, approvemon, approtue,approvetue, approwed, approvewed, approthr, approvethr, approfri, approvefri, approsat, approvesat, commen, months, SUM(nol)
FROM `pushkalit`.`approval`
WHERE (CONVERT(`approcode` USING utf8) LIKE '%"+user+"%')
AND ( appromon = DATE_FORMAT(NOW(), "%d/%m/%Y")
OR approtue = DATE_FORMAT(NOW(), "%d/%m/%Y")
OR approwed = DATE_FORMAT(NOW(), "%d/%m/%Y") )
Note that i inserted parens around your OR conditions, because i think this is actually what you intended to query.

Rails: Increase date by one or for tomorrow

I know it is very very simple but am not getting how to do it.
end_time = Time.new(Date.today.year, Date.today.month, Date.today.day, 8, 00, 00).strftime("%H:%M:%S")
But in above code i want tomorrow instead of today i.e. '+1 day'. How can i do it?
I tried:
end_time = Time.new(Date.today.year, Date.today.month, Date.today.day, 8, 00, 00).strftime("%H:%M:%S") + 1.day
or
end_time = Time.new(Date.tomorrow.year, Date.tomorrow.month, Date.tomorrow.day, 8, 00, 00).strftime("%H:%M:%S")
But no use. Can anybody answer it?
In rails you can use : end_time + 1.day or 1.day.from_now
Added specific case:
if #order.delievery_time.between?(start_time, end_time + 1.day)
#time = #order.delievery_time.strftime("%H:%M:%S")
end
if you want date in a date field
Simply use :-
= date_field_tag :date_of_journey, Date.tomorrow
or if you want to hold it in a variable use:-
date = Date.tomorrow

Rails ActiveRecord - how to fetch records between two dates

I have two date columns - from_date and to_date in a database table.
Example:
from_date: 2012-09-10
to_date: 2012-09-30
today: 2012-09-13
I need to fetch all records, if today's date is between from_date and to_date. How do I do that with a SQL query?
If I have loaded the respective record, I can easily decide, if today's date is between from_date and to_date, but I don't know how to fetch those records straight from the database table.
Check the Rails guides on Range conditions:
Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)
That will produce the following SQL:
SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
data = ModelName.where("today >= from_date AND today <= to_date")
A secure and easy way to do this would be:
Model.where(':date BETWEEN from_date AND to_date', date: Date.current)
you can use like this:
Data = Model.where("date(now()) between from_date and to_date")
data = ModelName.find(:all, :conditions => "today >= from_date and today <= to_date")
This should do the trick.
today = Date.today
data = ModelName.where("from_date <= ? AND to_date >= ?", today, today)
You could use below gem to find the records between dates,
This gem quite easy to use and more clear By star am using this gem and the API more clear and documentation also well explained.
ModelName.between_times(Time.zone.now - 3.hours, # all posts in last 3 hours
Time.zone.now)
Here you could pass our field also ModelName.by_month("January", field: :updated_at)
Please see the documentation and try it.
Ok, after a long search in google looking for a "rails way" to do a BETWEEN with two date fields and a variable, the most approximate solution I found is creating your own scope to do that.
in your ApplicationRecord write:
class ApplicationRecord < ActiveRecord::Base
scope :between_fields, -> (value, initial_date, final_date) {
where "('#{value}' BETWEEN #{initial_date} AND #{final_date})"
}
end
So now, wherever you need to do a between you can do:
#clients = Client.between_fields(params[:date], :start_date, :final_date)
# SELECT * FROM clients WHERE ('2017-02-16 00:00:00' BETWEEN start_date AND final_date)
You can combine it with others "where" to do your query as specific as you need.