I have to make an query on a table where the datetime field is of type datetimeoffset. The query itself is already difficult, but now working with conversions makes it even more complicated. What I want out of the table is to retrieve everything between 23:00 previous day to 07:00 the next morning for the past 2 weeks. I have tried numerous ways, but think I am just staring at a screen momentarily. Below is one of my last attempts before posting here, what am I missing here:
SELECT *
FROM Occurrences
WHERE SWITCHOFFSET(CreatedOn,'+01:00') >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0,
SWITCHOFFSET(CreatedOn,'+01:00') - 1), 0))
AND SWITCHOFFSET(CreatedOn,'+01:00') < DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0,
SWITCHOFFSET(CreatedOn,'+01:00')), 0))
ORDER BY CreatedOn DESC
Just note This is without the 2 weeks filter. Just wanted to see some results atleast, but get an error:
Operand type clash: datetimeoffset is incompatible with int
The CreatedOn has a entry like "2022-11-15 09:24:13.6096718 +01:00" and the type of field is a datetimeoffset(7)
This does work though in it simplest form:
SELECT TOP 1 SWITCHOFFSET(CreatedOn,'+01:00') FROM Occurrences ORDER BY CreatedOn DESC
SWITCHOFFSET(CreatedOn,'+00:01')seems wrong; that would be a 1 minute offset from UTC. Is that what you actually want? No one actually observes that.