'SQL : Get yesterdays day with a certain timestamp
i am trying to get yesterdays date in SQL SERVER with a certain timestamp.
I know how to get yesterdays date in SQL without the timestamp using the following query :
Which gives me every startdate starting from '00:00:00':
SELECT se.startdate
FROM sessions se
WHERE se.startdate >= DATEADD(day, -1, CAST(GETDATE() AS date))
Instead I want to get the yesterdays date with a certain timestamp. For this example every startdate starting from '06:00:00'(AM). Like shown below:
SELECT se.startdate
FROM sessions se
WHERE se.startdate >= '05-09-2022 06:00:00'
If I do it the way it was shown in the second example I would have to change the day manually, which would obviously repetitive.
Is there a way to combine the first example with second one so that we get always yesterdays date at '06:00:00' ? (OR ANY GIVEN TIME )
Solution 1:[1]
Might as well add another solution, DATETIMEFROMPARTS:
DECLARE @Yesterday date = DATEADD(DAY, -1, GETDATE());
SELECT DATETIMEFROMPARTS(YEAR(@Yesterday),MONTH(@Yesterday),DAY(@Yesterday),6,0,0,0);
Solution 2:[2]
For example 06:20:40 of the previous day:
select DATEADD(second, (6 * 60 + 20 ) * 60 + 40, cast(DATEADD(day, -1, cast(GETDATE() AS date)) as datetime)) t
Solution 3:[3]
you can do it this way:
SELECT DATEADD(day, DATEDIFF(day, 1, GETDATE()), '06:00:00')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Larnu |
| Solution 2 | Serg |
| Solution 3 | T Olaleye |
