Technology with opinion

Thursday, April 30, 2009

Deriving a Date Range for a Day

Many times the database will contain data with different times and we need to get all data for one day.  In .Net this is done by:
Console.WriteLine("Start Date: {0}", DateTime.Now.Date); 
Console.WriteLine("End Date: {0}", DateTime.Now.AddDays(1).Date.AddMilliseconds(-1)); 

This would output: 

Start Date: 4/30/2009 12:00:00 AM
End Date: 4/30/2009 11:59:59 PM

 Let's say in NHibernate we want a criteria expression to retrieve all objects with a DateTime that falls within an entire date (regardless of time)

return Session.CreateCriteria(typeof(Person))
    .Add(Expression.Between("DateOfBirth", dateOfBirth.Date, dateOfBirth.AddDays(1).Date.AddMilliseconds(-1)))
    .List< Person >();

This would return all People that were born on the same day (regardless of the time of birth) since the Time portion of the Date are usually stored in the database.


Brian said...

go PHP for making things a lot more simple. lol

pidofelen said...

good stuff, this saved me a headache!