Question

For my website I must select all messages sent between midnight (the previous night) and midnight (the next night). Basically, it's a 24 hours range.

I don't know how to do that as I store the date in a timestamp format in my DB.For example, last message was posted on 2013-10-18 11:23:35.

What I want is all message posted between 2013-10-18 00:00:00 and 2013-10-18 23:59:59. Is that possible, if yes, how could I do that ?

Was it helpful?

Solution

You can calculate the required time in T-SQL as :

-- for previous day mid night  as start time
declare @start_datetime datetime,@end_datetime datetime 
Select @start_datetime = DATEADD(d,0,DATEDIFF(d,0,GETDATE()))
-- for current day mid night as end time
Select @end_datetime = DATEADD(SS,86399,DATEDIFF(d,0,GETDATE()))

select @start_datetime, @end_datetime

and then use you column name to check whether it exists between these two values.

OTHER TIPS

To find out what happened between DatetimeA and DatetimeB, the sql keyword between is not your friend. It generally causes one to miss records. This construct is better.

where YourDateTimeField >= StartDateTime
and YourDateTimeField < JustAfterTheEndDateTime

In your case, you can simplify it with

where YourDateTimeField >= DateA
and YourDateTimeField < TheDayAfterDateA
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top