How to compare a date in ruby? - 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

Related

Searching between two dates with Ruby IMAP

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
}

Entity framework and datetime compare

Is possible to create linq query to find all records, which are in date range?
For example :
I have table with VacationStart, VacationEnd - both datetime and i need find all pending vacations to current date.
I am trying
context.Vacations..Where(x=> x.VacationStart >= DateTime.Now && x.VacationEnd < DateTime.Now)
but i getting 0 records...
Sample data 2011-10-27 08:30:00.000 2011-10-28 17:00:00.000
Current date : 2011-10-26 23:39:46.297
Where i do mistake?
Thanks
You are asking for vacations that start after NOW and end before NOW, Impossible. try asking and comparing a start time and end time that are different and where start time is less than the end time.
Gives only the vacations currently in progress.
var query = context.Vacations.Where(v => v.VacationEnd > DateTime.Now
&& v.VacationStart < DateTime.Now);
Gives vacations that haven not begun yet.
var query = context.Vacations.Where(v => v.VacationStart > DateTime.Now);
Gives Vacations that are in progress or still have not started.
var query = context.Vacations.Where(v => v.VacationEnd > DateTime.Now);
The last one doesn't filter any future vacations.

Filtering by Date (linq)

I have DateTime field named "repeat" in database. I want to take only records which Date in "repeat" is today.
I tried :
(...).Where(e => e.repeat.Value.Date.Day.Equals(DateTime.Now.Day));
or:
(...).Where(e => e.repeat.Value.Date.Day==DateTime.Now.Day);
but it doesn't work.
Any ideas?
Thanks,Kamil
"It doesn't work" is pretty vague, but currently you're checking the day of the week rather than the date. I would suggest using:
Date today = DateTime.Today;
var query = ....Where(e => e.repeat.Value.Date == today);
EDIT: It's not clear what the types involved here are - if repeat.Value is not itself a DateTime, you may want:
var query = ....Where(e => e.repeat.Value.Date.Date == today);
Give this a try:
(...).Where(e => (e.repeat >= DateTime.Today) && (e.repeat < DateTime.Today.AddDays(1)))
Compare short date ensures you the year/month/day are the same in one shot :
(...).Where(e => e.repeat.Value.Date.ToShortDateString() == DateTime.Now.ToShortDateString());
Expert Solution is: Use DbFunctions.CreateDateTime() in Linq Query.
var date = DateTime.Now.AddDays(-1).Date;
var actions = await _context.Set<Your_table>()
.AsNoTracking()
.Where(x => DbFunctions.CreateDateTime(x.YourColumn.Value.Year, x.YourColumn.Value.Month, x.YourColumn.Value.Day, 0, 0, 0) == date)
.ToListAsync();

Compare only Date in nHibernate Linq on a DateTime value

I trying to compare two dates (DateTime) in nHibernate linq:
query = query.Where(l => (l.datCriacao.Date == dtLote.Date)
but I am getting the error:
NHibernate.QueryException: could not resolve property: datCriacao.Date of: SAGP.Entities.Lote
Anyone knows how I can solve this? Thanks
I solved the problem doing a between with the dates:
DateTime initialDate, finalDate;
initialDate= DateEntity.Date;
finalDate= new DateTime(DateEntity.Year, DateEntity.Month, DateEntity.Day, 23, 59, 59);
query = query.Where(l => (((l.dateEntity>= initialDate) && (l.dateEntity<= finalDate))
This is super old, but I'd add to jaspion's example as:
query = query.Where(l => (l.datCriacao >= dtLote.Date && l.datCriacao < dtLote.Date.AddDays(1))
You can check the condition like this
var nextDay = DateTime.Today.AddDays(1);
query = query.Where(l => (l.datCriacao >= dtLote && l.datCriacao < nextDay);
here you'll get the records on dtLote date as we checking between dtLote and dtLote+1 day (00:00:00) we'll get today's date record only what ever may be the time...

Joins with multiple fields on GroupBy table data in LINQ query/method

I have to work out how to write the following SQL query usingLINQ query or method syntax. (Edit: This is to return a list of latest AgentActivities for all Agents).
SELECT
a.[AgentActivityId],
a.[AgentId],
a.[ActivityId],
a.[StartedAt],
a.[EndedAt],
a.[Version]
FROM
[dbo].[AgentActivity] a
INNER JOIN
(
SELECT
[AgentId],
MAX([StartedAt])[StartedAt]
FROM
[dbo].[AgentActivity]
WHERE
([StartedAt] > '2010/01/24 23:59:59')
AND ([StartedAt] < '2010/10/25')
GROUP BY
AgentId
)grouped
ON (a.[AgentId] = grouped.[AgentId]
AND a.[StartedAt] = grouped.[StartedAt])
Just to recap, here's how I interpret the question:
What you want is a list with the most recently started activity for an agent, with the added requirement that the activity must be started within a given date interval.
This is one way to do it:
// the given date interval
DateTime startDate = new DateTime(2010, 1, 24);
DateTime endDate = new DateTime(2010, 10, 25);
IEnumerable<AgentActivity> agentActivities =
... original list of AgentActivities ...
IEnumerable<AgentActivity> latestAgentActivitiesByAgent = agentActivities
.Where(a => a.StartedAt >= startDate && a.StartedAt < endDate)
.GroupBy(a => a.AgentId)
.Select(g => g
.OrderByDescending(a => a.StartedAt)
.First());
(If the question involves LINQ to SQL, there may be some gotchas. I haven't tried that.)

Resources