0

I'm working on a Room Scheduling application. We have this Room Check Out Rule that we need follow. All room check out should be 12:00 PM. If the check out date is after 12.00 PM it will be considered additional 1 day.

Below is my T-SQL code that returns 5 days.

  SELECT DATEDIFF(day, '3/12/2013 12:00:00 PM', '3/17/2013 3:00:00 PM'); 

If you see the code above the end date is 3:00:00 PM. How can I tweak this code to return 6 days instead of 5?

What if I have this code?

  SELECT CEILING(DATEDIFF(SECOND, '3/12/2013 02:00:00 PM' , '3/17/2013 12:50:36 PM') / (24.0 * 60 * 60))

The above code still returns 5 days instead of 6.

user2059064
  • 153
  • 3
  • 7
  • 17

3 Answers3

3
SELECT CEILING(DATEDIFF(SECOND, '3/12/2013 12:00:00 PM', '3/17/2013 12:00:01 PM') / (24.0 * 60 * 60))
polybios
  • 1,159
  • 8
  • 20
2

The correct way is to subtract 12 hours from StartDate and EndDate, then take a day-diff + 1:

declare @dateStart as datetime, @dateEnd as datetime
set @dateStart = cast('20130301 11:59:59 AM' as datetime)
set @dateEnd   = cast('20130301 12:01:01 PM' as datetime)

select 
  @dateStart, 
  @dateEnd

select days = 1 + datediff(d,@dateStart,@dateEnd)

select 
  days = 1 + datediff(d, dateadd(hh, -12, @dateStart), dateadd(hh, -12, @dateEnd))

returns this:

----------------------- -----------------------
2013-03-01 11:59:59.000 2013-03-01 12:01:01.000

days
-----------
1

days
-----------
2

Clearly the second formula is correct, not the first.

Pieter Geerkens
  • 11,775
  • 2
  • 32
  • 52
1

Perhaps you can count hours:

SELECT DATEDIFF(hour, '3/12/2013 12:00:00 PM', '3/17/2013 3:00:00 PM'); 

Therefore, 123 > 120 (or divided by 24 - 5.125 > 5) accounts for 6 days.