Search code examples
sql-serverhourgetdateminute

Select specific hour and minute from getdate() in SQL Server


Consider:

((DATEPART(HOUR, getdate()) BETWEEN 9 AND 15) or (DATEPART(HOUR, getdate())= 15 and (DATEPART(MINUTE, getdate()) between 00 and 30))) 

The above is the query using for fetching data between 9AM to 03:30PM and except 1 PM.

How can modify this query to fetch data between 09:30 AM to 03:30 PM and except 1 PM?


Solution

  • Converting to a time seems the easiest solution here.

    WHERE CONVERT(time,GETDATE()) >= '09:30:00' AND CONVERT(time,GETDATE())< '15:30:00'
      AND NOT(CONVERT(time,GETDATE())>= '13:00:00' AND CONVERT(time,GETDATE())< '14:00:00')
    

    Or you could do:

    WHERE ((CONVERT(time,GETDATE())>= '09:30:00' AND CONVERT(time,GETDATE())< '13:00:00')
       OR  (CONVERT(time,GETDATE())>= '14:00:00' AND CONVERT(time,GETDATE())< '15:30:00'))