How to create a time of 9pm today in SQL - sql

I am trying to get a smalldatetime value of "9pm today" in a query. I thought I could use
DATEADD(HOUR, 21, CONVERT(date, GETDATE()))
but SQL Server doesn't like that - I get the error
The datepart hour is not supported by date function dateadd for data
type date.
Suggestions for a workaround?

Pretty simple, just cast date back to datetime after casting to date.
Thus you'll get current_date 00:00:00 and then add 21 hours:
select dateadd(hh, 21, cast(cast(getdate() as date) as datetime))

it is because dateadd's 3rd parameter should be datetime type, not date.
SELECT DATEADD(HOUR, 21, CONVERT(datetime,CONVERT(date, GETDATE())))

just add 21 / 24.0 to todays date
Select dateadd(day, datediff(day, 1, getDate()), 1) + (21 / 24.0)
First part, dateadd(day, datediff(day, 1, getDate()), 1), strips time from getdate(),
second part, + (21 / 24.0), adds fractional part of day equal to 9 am
This works because internally, SQL Server represents datetimes as two integers, one for the date, (number of days since 1 Jan 1900), and a second integer for the time, (number of ticks since midnight), which it combines into a decimal value where the integer part is the date integer, and the decimal part is the fraction of one day, so if you add 0.5 to a date, you get noon on that day, etc.
or, for comparison, using dateadd for hours,
Select dateadd(hour, 21, dateadd(day, datediff(day, 1, getDate()), 1))

Related

SQL DATEADD Function for 7 days after the end of the last quarter

MS SQL Server: I'm trying to get 7 days after the end of the last quarter...
Here's what I have so far.
DATEADD(D, 0, DATEDIFF(D, 0, DATEADD(s,-1,DATEADD(q, 1, DATEADD(q, DATEDIFF(q, 0, GETDATE()) - 1, 0))))) AS LastDayOfLastFullQuarter
Your original expression was close (you needed to add 7 days, not 0):
------------------v
SELECT DATEADD(D, 7, DATEDIFF(D, 0, DATEADD(s,-1,DATEADD(q, 1, DATEADD(q, DATEDIFF(q, 0, GETDATE()) - 1, 0))))) AS SevenDaysAfterLastDayOfLastFullQuarter
But, good gravy, that's hard to read, and not just because of all the shorthand. Generally, it is better to find the beginning of the next period than the end of the current one. Subtracting a second from the beginning of this quarter won't always get you a date/time value in the previous quarter because some types round up.
Why not think about it as calculating 6 days after the beginning of the current quarter?
DECLARE #d date = GETDATE();
SELECT DATEADD(DAY, 6,
DATEFROMPARTS
(
YEAR(#d),
MONTH(#d)-((MONTH(#d)-1)%3),
1
)
);
Another way that is more like Steve's, if you don't like all the math:
DECLARE #d date = DATEADD(QUARTER,DATEDIFF(QUARTER,'20000101',GETDATE()),'20000101');
SELECT DATEADD(DAY, 6, #d);
I talk about both of these approaches here, and unfortunately the beginning of a quarter is not a calculation that's easy to write in a self-documenting way in T-SQL, so you get to choose between unintuitive methods (dateadd/datediff from some irrelevant date, or modulo and other math), and it gets more complicated if your fiscal calendar does not align with your cute dogs of 2020 calendar:
Simplify Date Period Calculations in SQL Server
But having thought on it a moment, this approach is only a few more characters but is a little more self-documenting without the modulo and other calculations:
DECLARE #d date = GETDATE();
SELECT DATEADD(DAY, 6,
DATEFROMPARTS
(
YEAR(#d),
CASE WHEN MONTH(#d) < 4 THEN 1 -- if Jan-Mar, want Jan
WHEN MONTH(#d) < 7 THEN 4 -- if Apr-Jun, want Jun
WHEN MONTH(#d) < 10 THEN 7 -- if Jul-Sep, want Jul
ELSE 10 -- if Oct-Dec, want Oct
END,
1
)
);
I talk about why you should spell out date-related values (e.g. don't use q and d and s and 0, though the last one is still a bad habit of mine) here:
Bad Habits to Kick : Using shorthand with date/time operations
Date Shorthand
And why you should always think about the beginnings instead of the ends of periods here:
What do BETWEEN and the devil have in common?
Do Not Use BETWEEN with Dates
This should do it too
select cast(dateadd(d, 7, dateadd(qq, datediff(qq, 0, getdate()), -1)) as date);
Results
2020-07-07
declare #date datetime = getdate();
select DATEADD(d, 6, DATEFROMPARTS(YEAR(#date), (MONTH(#date) - 1) / 3 * 3 + 1 , 1))
I would use:
select dateadd(month,
-2,
datefromparts(year(getdate()), ((month(getdate()) + 2) / 3) * 3, 7)
)

T-SQL Dynamic date range in WHERE clause (Last fiscal year + year to date)

I'm using the following WHERE clause to only load records from the last fiscal year plus a year to date.
Running without the WHERE clause, it takes 30seconds for 1mil records. With the WHERE clause, I had to stop it after 2hours.
Can you please share your thoughts
WHERE
([schema].[table].[DATE] >= DATEADD
(yy, - 1, DATEADD
(MONTH,(MONTH(GETDATE()) - 1) / 6 * 12 - 6,
CAST(CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME)
)
)
)
Declare #PastFiscalYear Date
Set #PastFiscalYear= DATEADD(yy, - 1, DATEADD(MONTH,(MONTH(GETDATE()) - 1) / 6 * 12 - 6,CAST(CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME)))
WHERE
([schema].[table].[DATE] >= #PastFiscalYear )
Can you try this
This will bring back data since the previous fiscal year start date. Just change the -3 to what ever your FY offset is. -3 is for October.
[schema].[table].[DATE] >= DATEADD(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, -1, GETDATE())), 0))

Getdate() functionality returns partial day in select query

I have a query -
SELECT * FROM TABLE WHERE Date >= DATEADD (day, -7, -getdate()) AND Date <= getdate();
This would return all records for each day except day 7. If I ran this query on a Sunday at 17:00 it would only produce results going back to Monday 17:00. How could I include results from Monday 08:00.
Try it like this:
SELECT *
FROM SomeWhere
WHERE [Date] > DATEADD(HOUR,8,DATEADD(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))) --7 days back, 8 o'clock
AND [Date] <= GETDATE(); --now
That's because you are comparing date+time, not only date.
If you want to include all days, you can trunc the time-portion from getdate(): you can accomplish that with a conversion to date:
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -convert(date, getdate())
AND Date <= convert(date, getdate());
If you want to start from 8 in the morning, the best is to add again 8 hours to getdate.
declare #t datetime = dateadd(HH, 8, convert(datetime, convert(date, getdate())))
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -#t) AND Date <= #t;
NOTE: with the conversion convert(date, getdate()) you get a datatype date and you cannot add hours directly to it; you must re-convert it to datetime.
Sounds like you want to remove the time. Correct? If so then do the following.
SELECT * FROM TABLE WHERE Date >= (DATEADD (day, -7, -getdate()) AND Date DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))

Julian Date to Datetime SQL Server

I have the following columns in a table
Year Julian_Day Time_HHMM Seconds Decimal_Day
2015 271 2000 0 0.7415013
The ouput datetime is "2015-09-28 20:00:00"
I tried to figure out how to convert those parameters to datetime but I havent had luck.
Any help is welcome
You should be able to do this by nesting calls to the DATEADD function for the various components:
SELECT DATEADD(SECOND, [Seconds], DATEADD(MINUTE, CAST(RIGHT([Time_HHMM], 2) AS INT), DATEADD(HOUR, CAST(LEFT([Time_HHMM], 2) AS INT), DATEADD(DAY, [Julian_Day] - 1, DATEADD(YEAR, [Year] - 1900, 0)))))
FROM YourTable
Note I have not used the Decimal_Day column.
DATEADD takes integer parameters for the components, so you may need some additional casting on the columns to INT, if they are currently of type VARCHAR.
[https://social.msdn.microsoft.com/Forums/sqlserver/en-US/47d773c3-dae2-41cc-8770-5f2f24a1c665/julian-date-to-datetime-conversion][1]
SELECT DATEADD(YEAR, #JulianDate / 1000 - 1900, #JulianDate % 1000 - 1)

Add time stamp to date in SQLserver

Below fetches the last monday from the current date.
SELECT cast (DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0) as datetime)
but it displays date as timestamp all zeros like this
2014-05-26 00:00:00.000
I want the time stamp to be at 6 am like this
05-26-2014 06:00:00
or else its ok even if I get the the exact last monday date with the current GETDATE() timestamp.
Thank you for the help!
Adding 6 hours
SELECT cast (DATEADD(HH,6,DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0)) as datetime)
You can convert it using one of the many built-in formats.
This will display it in the format:
MM-DD-YYYY 06:00:00
and still fetch the last Monday date you want.
SELECT CONVERT(VARCHAR, DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0), 110) + ' 06:00:00'