Searching between two dates with Ruby IMAP - ruby

I am new to Ruby, I'm trying to return the number of emails between 9am and 11am.
For example.
#received_today = imap.search(["SINCE", #today.strftime("%d-%b-%Y-%H"):"BEFORE", #today.strftime("%d-%b-%Y-%H")]).count.to_s
I know this is wrong, but it's my closest guess on how to do this. Any help would be highly appreciated.

Maybe something like this:
require 'date'
start_time = Net::IMAP.format_datetime(DateTime.strptime("09:00", "%H:%M"))
end_time = Net::IMAP.format_datetime(DateTime.strptime("11:00", "%H:%M"))
#received_today = imap.search(["SINCE", start_time, "BEFORE", end_time ]).count
UPDATE:
Try #2 :)
Since imap SEARCH command ignores the time part in SINCE and BEFORE conditions this should work:
require 'date'
today = Net::IMAP.format_date(Date.today)
start_time = DateTime.strptime("09:00", "%H:%M")
end_time = DateTime.strptime("11:00", "%H:%M")
#received_today = imap.search(["ON", today]) # get sequence nums of todays emails
# fetch the INTERNALDATE-s and count the ones in the timeframe
count = imap.fetch(#received_today, "INTERNALDATE").count{ |data|
time = DateTime.parse(data.attr["INTERNALDATE"])
time.between? start_time, end_time
}

Related

How to check if event's date is within a date range?

I have events (from an Event model) that have a starts_at: value in the form of a datetime. e.g.:
2016-02-18 11:00:00:00000
What I want to be able to do is check whether an event is starting this week.
I want to be able to make a list of events that are occuring this week (starting from the latest Monday).
#events = #calendar.events.where( ... )
I thought something along the lines of this:
start_week = Date.today.beginning_of_week(:monday).day()
end_week = Date.today.beginning_of_week(:monday).day()+6
range = start_week..end_week
#events = #calendar.events.where(starts_at: in range)
But it doesn't take into account the month or year. Also I'm not sure how to write the 'where' clause. How should I go about doing this? Thanks
Try this:
start_week = Date.today.beginning_of_week(:monday)
end_week = Date.today.beginning_of_week(:monday)+6
range = start_week..end_week
#events = #calendar.events.where(starts_at: range)
Assuming you want all the events from the current week, something like this should work:
#events = #calendar.events.where(starts_at: Time.zone.today.all_week)
all_week returns a Date range covering the current week.

How to compare a date in ruby?

I am running a SQL query which returns some orders each having a date. I want to check which orders were made on current date ?
I am able to do so by:
orders = Order.find_by_sql(query).reject {|o|
today = Time.now
end_of_today = Time.local(today.year, today.month, today.day, 23, 59, 59)
start_of_today = Time.local(today.year, today.month, today.day, 00,00,00 )
o.date > end_of_today
o.date < start_of_today
}.sort_by {|o|
o.delivery_date
}
'orders' contain all the orders which were made at any time Today.
Is there a simpler way of doing this in ruby ?
To get the orders made on the current date, you can do the following:
orders = Order.where("date >= ?", Time.zone.now.beginning_of_day).order(:delivery_date)
Hope this helps!
use DateTime.now.beginning_of_day
Order.where('date >= ?', DateTime.now.beginning_of_day).order(:delivery_date)
I think you are looking for this, it will cover all orders for today
orders = Order.where("created_at <= ? AND created_at >= ?", Time.zone.now.end_of_day, Time.zone.now.beginning_of_day).order(:delivery_date)
Now you are getting all the orders from the database (depends on what string is in the query) and then filtering the array, which is not the most efficient way if you have a large database. Much better way is doing this on SQL side.
Just use pure string conditions:
# Or set it to any other date in the past
target_date = Time.zone.now
orders = Order.find_by_sql(query)
.where("date >= ?", target_date.beginning_of_day)
.where("date <= ?", target_date.end_of_day)
.order(:delivery_date)
More details here: http://guides.rubyonrails.org/active_record_querying.html#pure-string-conditions
More info on Active Support DateTime methods: http://api.rubyonrails.org/classes/DateTime.html#method-i-beginning_of_day

Ruby .has_key? not seemingly working?

This is a strange problem, because I can write what looks like totally identical code in PHP that works fine, yet Ruby is failing without explanation. If someone could offer advice, I'd be really happy.
So I am iterating over a database table in Ruby. Every row has a date field. I want to generate a line graph from this table. So if there are 30 lines with "1995" in the date, I want my hash to end up with "1995": 30 as its content. Then I can feed that data to a JS chart library.
So my code right now is
db.execute("SELECT date FROM events") do |row|
graphdata = {}
year = row[0][0...4] # Gets first four digits of date, so 1995, 1996, 1997, etc.
if graphdata.has_key?(year) then
graphdata[year] += 1
else
graphdata[year] = 1
end
end
Pretty simple. If there's already a key for that year, increment it; if there's not, create it with an initial value of 1.
But the result I get is
{"1997"=>1}
{"1997"=>1}
{"1998"=>1}
{"1998"=>1}
{"1998"=>1}
{"1998"=>1}
{"1998"=>1}
{"1998"=>1}
I'm new to Ruby, but I can't understand why. The logic seems totally sound. I even wrote the same thing in PHP, which is working fine.
$results = $db->query("SELECT date from events order by date asc");
$graphdata= array();
while ($row = mysqli_fetch_row($results)) {
$year = substr($row[0],0,4);
if (array_key_exists($year,$graphdata)) {
$graphdata[$year]++;
} else {
$graphdata[$year] = 1;
}
}
What am I doing wrong?
Place graphdata = {} outside the main loop. Otherwise you are re-initializing it to the empty hash on each new row.
Also, you could probably just use a default value:
graphdata = Hash.new(0)
db.execute("SELECT date FROM events") do |row|
year = row[0][0...4] # Gets first four digits of date, so 1995, 1996, 1997, etc.
graphdata[year] += 1
end

Generate date objects in hour steps between two given dates

Given are two timestamps in the format YYYYMMDDHH, which are perfectly parseable by DateTime.strptime.
What I want to create is a list of strings in the given format from above in one hour steps, starting from the first date up to the second date.
Example input: 2013011515 and 2013011822.
Expected output: ['2013011515','2013011516','2013011517','2013011518', ... , '2013011820', '2013011820', '2013011821', '2013011822']
Is there any ruby library or core functionality to accomplish this task?
You can use step with an hourly resolution if you use ruby 1.9:
date1 = DateTime.strptime('2013011522', '%Y%m%d%H')
date2 = DateTime.strptime('2013011622', '%Y%m%d%H')
date_range = date1.step(date2, 1.0/24).to_a
Alternatively, on ruby 1.8.7, use a loop
date1 = DateTime.strptime('2013011522', '%Y%m%d%H')
date2 = DateTime.strptime('2013011622', '%Y%m%d%H')
new_date = date1
date_range = [date1]
date_range << (new_date += 1.0/24) while new_date <= date2
#!/usr/bin/env ruby
dt_from = "2013011515"
dt_to = "2013011822"
require 'date'
date_from = Date.parse(dt_from[0,8])
date_to = Date.parse(dt_to[0,8])
res = []
date = date_from
while (date <= date_to)
if date == date_from
hours = (dt_from[8,2].to_i..23).to_a
elsif date == date_to
hours = (0..dt_to[8,2].to_i).to_a
else
hours = (0..23).to_a
end
hours.each {|h| res << "#{date.strftime('%Y%m%d')}#{"%02d" % h}"}
date += 1
end
puts res.inspect

Finding start and end date of month

I found code example for finding the start and end day of the current month I'm in. I tried to jump start this code, but am having a hard time figuring out what I have gone wrong.
month = params[:month].to_i
date_start = DateTime.new Date.today.year, params[:month], 1
date_end = (date_start >> 1) + 1 # will add a month and a day
#trips = Trip.all :date => date_start..date_end
I'm not 100% sure what to feed into params. Hope someone can help.
I am not sure if I understand your question correctly, maybe what you need is this? :
month = 9
date_start = Date.new(Time.now.year, month, 1)
date_end = date_start.next_month - 1
params should contains month(numeric) i.e between 1 - 12
For e.g params = {:month => '4'}
Also in second line use month instead of params[:month]

Resources