How do I add Hours, mins, seconds to dateadd sql? - sql

I want to get an entire date
So today would be 7/7/2010 12:00:00 am to 7/7/2010 11:59:59 pm
So that should be the full 24 hours since 12:00:00 am would be the 8th then.
So I have this
select DATEADD(??, ??, DATEDIFF(dd, 0, GETUTCDATE()))
How do I make it add 23 hours 59mins and 59seconds to it?

DECLARE #start DATETIME
DECLARE #end DATETIME
SET #start = DATEADD(dd, 0, DATEDIFF(dd, 0, GETUTCDATE()))
SET #end = DATEADD(dd, 1, DATEADD(ms, -3, #start))

Try this:
DATEADD(second, -1, DATEADD(DAY, 1,"7/7/2010 12:00:00"))

Related

Truncate timestamp

I would like into a stored procedure, truncate timestamp input values at the top hour or at the lower hour.
For example, if my input values are 2020-02-12 06:56:00 and 2020-02-12 07:14:00, I would like to transforme it in 2020-02-12 06:00:00 and 2020-02-12 08:00:00
Is a cast function can work?
You can construct the new datetimes from the parts that you want of your original datetimes.
declare #start datetime = '2020-02-12 06:56:00'
declare #end datetime = '2020-02-12 07:14:00'
select #start as OriginalStart,
#end as OriginalEnd,
datetimefromparts(year(#start), month(#start), day(#start), datepart(hour, #start), 0, 0, 0) as TruncatedStart,
dateadd(hour, 1, datetimefromparts(year(#end), month(#end), day(#end), datepart(hour, #end), 0, 0, 0)) as TruncatedEnd
The first truncation of the interval is the lower hour, and the second one adds an additional hour so it returns the higher hour.
PS: If what you want is to round to the nearest hour, then you can add 30 minutes and truncate :
declare #date datetime = '2020-02-12 06:56:00'
set #date = dateadd(minute, 30, #date)
select datetimefromparts(year(#date), month(#date), day(#date), datepart(hour, #date), 0, 0, 0) as NearestHour
or in a single step (using Lepetit's shortcut for truncation) :
declare #date datetime = '2020-02-12 06:56:00'
select dateadd(hour, datediff(hour, 0, dateadd(minute, 30, #date)), 0) AS NearestHour
This is a simpler solution:
declare #start datetime = '2020-02-12 06:56:00'
declare #end datetime = '2020-02-12 07:14:00'
select #start as OriginalStart,
#end as OriginalEnd,
dateadd(hour, datediff(hour, 0, #start), 0) as TruncatedStart,
dateadd(hour, datediff(hour, 0, dateadd(hour, 1, #end)), 0) as TruncatedEnd
In both cases the function substracts the hour part from the original timestamp. For the TruncatedEnd, one hour is added, so that the result is the subsequent hour.
Using a bit of arithmetic calculation, convert to hours with decimal and use floor() and ceiling() to perform the round up / down
first it find the time different with 00:00:00 in terms of second. convert(date, date_col) convert the datetime to date, so effectively it is 00:00:00
datediff(second, convert(date, date_col), date_col)
then you divide by 60 x 60 = 3600 seconds. Gives you fraction of hours
then you use floor() or ceiling() to perform the rounding
and lastly you add that back to the date (convert(date, date_col))
Final query
select *,
RoundDown = convert(datetime, convert(date, date_col))
+ dateadd(hour, floor(datediff(second, convert(date, date_col), date_col) / (3600.0)), 0),
RoundUp = convert(datetime, convert(date, date_col))
+ dateadd(hour, ceiling(datediff(second, convert(date, date_col), date_col) / (3600.0)), 0)
from (
values
('2020-02-12 06:56:00'),
('2020-02-12 07:14:00')
) d (date_col)
/*
2020-02-12 06:56:00 2020-02-12 06:00:00 2020-02-12 07:00:00
2020-02-12 07:14:00 2020-02-12 07:00:00 2020-02-12 08:00:00
*/
EDIT : a much simpler query below
find the different in minute divide by 60.0 minutes to get different in terms of hour (with decimal places) and then apply floor or ceiling. Finally add that result back
select getdate() as Now,
dateadd(hour, floor(datediff(minute, 0, getdate()) / 60.0), 0) as RoundDown,
dateadd(hour, ceiling(datediff(minute, 0, getdate()) / 60.0), 0) as RoundUp

Week of the Month in SQL

DECLARE #date DATETIME= GETDATE()
SELECT DATEDIFF(WEEK,
DATEADD(WEEK,
DATEDIFF(WEEK, 0,
DATEADD(MONTH, DATEDIFF(MONTH, 0, #date), 0)),
0), #date - 1) + 1
What is purpose of 0 as a parameter in the datediff() function?
The specific answer to your question is that the 0 is just a way to get the beginning of the month:
dateadd(month, datediff(month, 0, #date), 0)
This is one method to do this in SQL Server, because it does not offer a "date truncate" function. I prefer:
dateadd(day, 1 - day(#date), #date)
(Although admittedly this is a wee bit more complicated if #date has a time component.)
However, a much simpler way to do this is:
select (day(#date) - 1) / 7) as week_of_month
Below gets the number of months from a reference point
datediff(month, 0, #date)
Then it is used to add to the reference date back to reach the first day of the month
dateadd(month,
datediff(month, 0, #date),
0)
So it is used to find the first day of the current month
declare #date datetime = getdate()
select
getdate(),
datediff(month, 0, #date),
dateadd(month,
datediff(month, 0, #date),
0)

Retrieving time period t-sql

I have a stored procedure set up in such a way as to get the results for today
so
DECLARE #Start DATETIME
DECLARE #End DATETIME
SET #Start = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
SET #End = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1)
PRINT #Start
PRINT #End
gives me the time period
May 30 2016 12:00AM
May 31 2016 12:00AM
How can I modify the clause as to give me the period
May 29 2016 5:30PM(Previous day)
May 31 2016 12:00AM(Today)
Kind regards
Try this solution:
SET #Start = DATEADD(MINUTE, 30, DATEADD(HOUR, 17, DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), -1)))
SET #End = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1)
DECLARE #Start DATETIME
DECLARE #End DATETIME
SET #Start = GETDATE()-1
SET #End = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1)
PRINT #Start
PRINT #End
dateadd(day, -1, getdate())
May be just use the DateAdd like above.

SQL timestamp between hours that fall across midnight

I'm trying to find all records that would fall with in a current time period based on the current time. For example the current time is 12:30am and I need all the records from the previous day starting at 6:00pm till current time. Very new to SQL and any help would be appreciated.
Below is a screenshot of the table and the column of interest is the timestamp (datetime). I have not tried really anything concrete, am still struggling with just trying to figure out how I would go about it.
Table
The following query returns "yesterday at 6 PM":
select DATEADD(hh, -6, DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))
The inner DATEADD gets "today at midnight" (basically just truncates the time part from "now". Try running the following by itself to see this:
select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
The outer DATEADD then subtracts 6 hours from "today at midnight" to get "yesterday at 6 PM".
So, to get all records from a table with a time greater than yesterday at 6 PM you would put this expression in a WHERE clause, like this:
select * from MyTable
where MyDateField > DATEADD(hh, -6, DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))
The options to manipulate dates in SQL are limited only by your imagination :)
For example, in your comment below, you want to filter on "current shift", which could be 6AM-6PM or 6PM-6AM, depending on current time. This would be more complicated, but still doable, like this:
select * from MyTable
where MyDateField >=
case
when datepart(hh, getdate()) < 6 then -- if before 6AM
--yesterday at 6 PM
dateadd(hh, -6, dateadd(dd, datediff(dd, 0, getdate()), 0))
when datepart(hh, getdate()) between 6 and 18 then -- if between 6AM and 6PM
--today at 6 AM
dateadd(hh, 6, dateadd(dd, datediff(dd, 0, getdate()), 0))
else -- if after 6 PM
--today at 6 PM
dateadd(hh, 18, dateadd(dd, datediff(dd, 0, getdate()), 0))
end
and MyDateField <
case
when datepart(hh, getdate()) < 6 then -- if before 6AM
--today at 6 AM
dateadd(hh, 6, dateadd(dd, datediff(dd, 0, getdate()), 0))
when datepart(hh, getdate()) between 6 and 18 then -- if between 6AM and 6PM
--today at 6 PM
dateadd(hh, 18, dateadd(dd, datediff(dd, 0, getdate()), 0))
else -- if after 6 PM
--tomorrow at 6 AM
dateadd(hh, 30, dateadd(dd, datediff(dd, 0, getdate()), 0))
end
Notice how this reuses the same calculation for "today at midnight" and simply adds a variable number of hours to that, depending on the current hour of the day, which is where datepart comes in handy.
Good luck!
select dateadd(hour,-6,cast(cast(getdate() as date) as datetime))
This may be a bit convoluted, but the above is getting the current date and going back 6 hours. This will return 6PM from "yesterday".
You could take records where TIMESTAMP > the above.

How to get the last month data and month to date data

Need help in writing the query to get the last month data as well as month to date data.
If today's date is Mar 23 2011, I need to retrieve the data from last month and the data till todays date(means Mar 23 2011).
If date is Apr 3 2011, data should consists of March month data and the data till Apr 3rd 2011.
Thanks,
Shahsra
Today including time info : getdate()
Today without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month : DATEADD(month, datediff(month, 0, getdate())-1, 0)
so most likely
WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
AND dateColumn < DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Step back one month, subtract the number of days to the current date, and add one day.
WHERE
DateField <= GetDate() AND
DateField >= DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)
To remove the time quickly, you can use this
Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )
So the second part would be (without time)
DateField >= Cast( Floor( Cast( (DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)) AS FLOAT ) ) AS DATETIME )
Select Column1, Column2 From Table1
Where DateColumn <= GetDate() AND
DateColumn >= DATEADD(dd, - (DAY(DATEADD(mm, 1, GetDate())) - 1), DATEADD(mm, - 1, GetDate()))
Edit: +1 to Russel Steen. I was posting mine before I knew he had posted.
Very helpful page
declare #d datetime = '2011-04-03';
declare #startDate datetime;
select #startDate =
CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,#d),113),8) AS datetime);
select #startDate;