Construct DateTime using today's date at a specific time - sql-server

I'd like to get 4:30 PM of the current day. Hard-coding this way doesn't work:
SELECT '07242012 16:30:00.000'
This is proving to be more difficult than I thought it would be. How do I approach this?

SQL Server 2000 / 2005:
SELECT DATEADD(MINUTE, 30, DATEADD(HOUR, 16, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP)));
-- or
SELECT DATEADD(MINUTE, (16*60) + 30, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP))
-- or
SELECT CONVERT(DATETIME, CONVERT(CHAR(9), CURRENT_TIMESTAMP, 112) + '16:30');
SQL Server 2008+:
SELECT CONVERT(DATETIME, CONVERT(DATE, CURRENT_TIMESTAMP)) + '16:30';
SQL Server 2012:
SELECT SMALLDATETIMEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE()), 16, 30);

Probably the easiest thing to do is to cast the current date/time to a date (stripping the time off), cast it back to a datetime to allow use of datetime's overloaded + (plus) and, finally cast your desired textual time to a datetime. As follows:
select cast(cast(sysutcdatetime() as date) as datetime) + cast('16:30' as datetime)
returns (when run on 11th Jan 2018):
2018-01-11 16:30:00.000

You can construct this as you like with day, hour, minute etc.
SELECT CURDATE() - interval 1 DAY + interval 2

select(dateadd(day, datediff(day, 0, getdate()), 0) + '20:00') as specified_date
specified_date - Output Column name
20:00 - Specified time(24 hr Format -Default)
getdate() - To get Today's date.

Related

Selecting column values based on minutes [duplicate]

In SQL server 2008, I would like to get datetime column rounded to nearest hour and nearest minute preferably with existing functions in 2008.
For this column value 2007-09-22 15:07:38.850, the output will look like:
2007-09-22 15:08 -- nearest minute
2007-09-22 15 -- nearest hour
declare #dt datetime
set #dt = '09-22-2007 15:07:38.850'
select dateadd(mi, datediff(mi, 0, #dt), 0)
select dateadd(hour, datediff(hour, 0, #dt), 0)
will return
2007-09-22 15:07:00.000
2007-09-22 15:00:00.000
The above just truncates the seconds and minutes, producing the results asked for in the question. As #OMG Ponies pointed out, if you want to round up/down, then you can add half a minute or half an hour respectively, then truncate:
select dateadd(mi, datediff(mi, 0, dateadd(s, 30, #dt)), 0)
select dateadd(hour, datediff(hour, 0, dateadd(mi, 30, #dt)), 0)
and you'll get:
2007-09-22 15:08:00.000
2007-09-22 15:00:00.000
Before the date data type was added in SQL Server 2008, I would use the above method to truncate the time portion from a datetime to get only the date. The idea is to determine the number of days between the datetime in question and a fixed point in time (0, which implicitly casts to 1900-01-01 00:00:00.000):
declare #days int
set #days = datediff(day, 0, #dt)
and then add that number of days to the fixed point in time, which gives you the original date with the time set to 00:00:00.000:
select dateadd(day, #days, 0)
or more succinctly:
select dateadd(day, datediff(day, 0, #dt), 0)
Using a different datepart (e.g. hour, mi) will work accordingly.
"Rounded" down as in your example. This will return a varchar value of the date.
DECLARE #date As DateTime2
SET #date = '2007-09-22 15:07:38.850'
SELECT CONVERT(VARCHAR(16), #date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), #date, 120) --2007-09-22 15
I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:
CAST(YourValueHere as smalldatetime);
For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.
Select convert(char(8), DATEADD(MINUTE, DATEDIFF(MINUTE, 0, getdate), 0), 108) as Time
will round down seconds to 00

Get results for one day back in sql server

I am trying to get results from 1 day back, for example if i have a job that runs today at 1:00:00 am the 22/05/2018 i want it to get back the results for the 21/05/2018 00:00:00 am to 21/05/2018 23:59:59 pm.
i tried the follwing
select *
from table
where CreatedDateTime BETWEEN DATEADD(day, -1, GETDATE()) AND DATEADD(day, -0, GETDATE()) // it brings back everything from yesterday and today
example of how my created date time is stored in the db 2018-05-21 16:39:09.4830000
The bewteen operator filters the dates based on >= and <=
You need :
select *
from table
where CreatedDateTime >= DATEADD(day, -1, GETDATE()) AND
CreatedDateTime < GETDATE();
I suspect you would need cast(... as date) if so, the you can directly express this as
select *
from table
where cast(CreatedDateTime as date) = cast(DATEADD(day, -1, GETDATE()) as date);
Here is a good BLOG on filtering date range in query.
SELECT *
FROM table
WHERE CreatedDateTime BETWEEN GETDATE() -1 AND GETDATE()

How to format a date with my own time part in SQL

I'm working on a SQL query which returns a integer which is the number of minutes between two given dates as follows
DATEDIFF(mi, date_one, getdate())
The above query returns difference in two dates in minutes but for getdate() I would want to supply my own time.
For example, consider
date_one= 2015-12-29 13:39:03.000
getdate() return current date and time ie., 2015-12-29 14:33:50.000
But, I want to change time part in getdate() to some 10:00:00.00 so that the getdate() is 2015-12-29 10:00:00.00 by passing an hour integer say 10.
May I know a good way to do that?
This will use getDate, but let you set your own hour. Just replace that second parameter (which is 10 with whichever hour you want). Use this expression in place of getDate() in your dateDiff function.
DATEADD(hh, 10, DATEADD(d, DATEDIFF(d, 0, getDate()), 0))
You can also add minutes, seconds, milliseconds, etc. to get what you need.
Here I am adding 633 minutes to make it 10:33 (change the first parameter to mi for minutes).
select DATEADD(mi, 633, DATEADD(d, DATEDIFF(d, 0, getDate()), 0))
See the documentation for other value for the first parameter: https://msdn.microsoft.com/en-us/library/ms186819.aspx
Here is how to use it:
DATEDIFF(mi, getDate(),
DATEADD(mi, 633, DATEADD(d, DATEDIFF(d, 0, getDate()), 0))
)
This will give you the minutes from the current time to 10:33 on the current day. Here is a sqlfiddle: http://sqlfiddle.com/#!6/9eecb7/5407
I find this function useful:
CREATE FUNCTION [dbo].[StripTimeFromDateTime]
(
#date DateTime
)
RETURNS DateTime
AS
BEGIN
RETURN DATEADD(dd, DATEDIFF(dd, 0, #date), 0)
END
This will knock the time off a datetime leaving it at 00:00:00.000. Then you can:
SELECT DATEADD(hour, 10, dbo.StripTimeFromDateTime(GetDate()))
Notice the example below:
select
cast('2015-12-28 12:15:00' as datetime),
getdate(),
cast(cast(convert(date, getdate()) as varchar(20)) + ' 10:00:00' as datetime);
|----------------------------|----------------------------|----------------------------|
| December, 28 2015 12:15:00 | December, 29 2015 20:42:35 | December, 29 2015 10:00:00 |
An example like the one you used:
with example as (
select cast('2015-12-28 12:15:00' as datetime) as date_one
)
select
date_one,
cast(cast(convert(date, getdate()) as varchar(20)) + ' 10:00:00' as datetime) as myown,
datediff(
mi,
date_one,
cast(cast(convert(date, getdate()) as varchar(20)) + ' 10:00:00' as datetime)
) as minutes
from example;
Result:
| date_one | myown | minutes |
|----------------------------|----------------------------|---------|
| December, 28 2015 12:15:00 | December, 29 2015 10:00:00 | 1305 |
Example on SQLFiddle: http://sqlfiddle.com/#!3/9eecb7/6599
The reason I used varchar is to have flexibility of typing a time such as '10:15:00' or other variations of time.
This one-liner will gives the current date with the time part replaced with the constant you want
select cast(cast(getdate() as date) as datetime) + cast(cast('10:00:00' as time) as datetime)
How this works:
Cast the getdate() result to date and then back to datetime to get the current date without the time.
select cast(cast(getdate() as date) as datetime)
Cast '10:00:00' to time and then to datetime to get 10:00:00 as datetime.
select cast(cast('10:00:00' as time) as datetime)
Add the two
select cast(cast(getdate() as date) as datetime) + cast(cast('10:00:00' as time) as datetime)
That's all
select DATEADD (hh,10, CONVERT(Datetime, CONVERT (date, GETDATE())))
First remove time and then add 10 hours.

Select records created in a 24 hour time-frame

I'm trying to query our database to find all records that were created between 6am yesterday and 6am today. This will be run in a report at any point during the day so set times/dates are useless.
I have this so far:-
SELECT * FROM DaySummaryDetail DSD
WHERE DSD.FromDateTime BETWEEN DATEADD(DAY, -1, GetDate())
AND DATEADD(Day, 1, GetDate())
But obviously this only works for 24 hours ago from right now until right now. I can't figure out how to apply a time as well as date.
Every example I find online seems slightly different and uses set dates/times ie, >= 20/02/2015 06:00:00.
I normally use Oracle SQL which would simply work using this:-
ptt.mod_date_time >= TRUNC (SYSDATE - 1) - 2 / 24
AND ptt.mod_date_time <= TRUNC (SYSDATE - 1) + 22 / 24
This would return results from 10pm to 10pm but the format appears totally different in SQL Server.
You can get the datetime values you are after by doing the following:
SELECT DATEADD(HOUR,6,CONVERT(DATETIME, CONVERT(DATE ,GETDATE()))) Today6AM,
DATEADD(HOUR,-18,CONVERT(DATETIME, CONVERT(DATE ,GETDATE()))) Yesterday6AM
By doing this: CONVERT(DATE ,GETDATE()) you are stripping off the time portion of today's date. Converting it back to datetime gives you midnight for today.
The query adds 6 hours to midnight of the current day for 6am today and subtracts 18 hours from midnight of the current day to give you 6am on the previous day.
Output:
Today6AM Yesterday6AM
================================================
2015-02-20 06:00:00.000 2015-02-19 06:00:00.000
So adding that to your query:
SELECT *
FROM DaySummaryDetail DSD
WHERE DSD.FromDateTime
BETWEEN DATEADD(HOUR,-18,CONVERT(DATETIME, CONVERT(DATE ,GETDATE())))
AND DATEADD(HOUR,6,CONVERT(DATETIME, CONVERT(DATE ,GETDATE())))
DECLARE #StartTimestamp datetime
DECLARE #EndTimestamp datetime
DECLARE #HourPartOfSearchRange nvarchar(6)
SET #HourPartOfSearchRange = ' 06:30'
SET #StartTimestamp =
CAST((CONVERT(varchar(11), DATEADD(DAY,-1,#CurrentUTCDateTime), 106) + #HourPartOfSearchRange) AS datetime)
SET #EndTimestamp =
CAST((CONVERT(varchar(11), #CurrentUTCDateTime, 106) + #HourPartOfSearchRange) AS datetime)
SELECT * FROM dbo.Test Where Timestamp Between #StartTimestamp AND #EndTimestamp
today 6am is
dateadd(hour,6,cast(cast(getdate() as date) as datetime))
cast(getdate() as date) truncates the timepart, cast it back as datetime because dateadd won't add hours otherwise and add 6hours
One solution would be like so:
select *
from DaySummaryDetail DSD
where DSD.FromDateTime between cast(cast(cast(getdate()-1 as date) as varchar(30)) + ' 06:00:00.000' as datetime)
and cast(cast(cast(getdate() as date) as varchar(30)) + ' 06:00:00.000' as datetime)
This should help ...
SELECT DATEADD( hour, 6, CAST(CAST(GETDATE(), AS Date) AS DateTime) ) AS 'Today#6am'
SELECT DATEADD( hour, 6, CAST(CAST(GETDATE()-1, AS Date) AS DateTime) ) AS 'Yesterday#6am'
In SQL Server 2012 you can use SMALLDATETIMEFROMPARTS to construct a datetime value that is today at 6am like this:
SMALLDATETIMEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE()), 6, 0)
Output: 2015-02-20 06:00:00
then you can use the above expression in place of GETDATE() in the WHERE clause:
DECLARE #TodayAt6AM DATETIME = SMALLDATETIMEFROMPARTS(YEAR(GETDATE()),
MONTH(GETDATE()),
DAY(GETDATE()),
6,
0)
SELECT *
FROM DaySummaryDetail DSD
WHERE DSD.FromDateTime BETWEEN DATEADD(DAY, -1, #TodayAt6AM) AND
DATEADD(Day, 1, #TodayAt6AM)

Increase Date to specific day of the following month

I want to take the current date and increase it to the 15th of the following month.
[<Date> #dmmm 15, yyyy]
Result:
Oct 15, 2012
DESIRED RESULT:
Nov 15, 2012
Thank you in advance for your help!!
Well, if the date you're starting with is the 15th, then you can perform this operation:
SELECT DATEADD(mm, 1, [DateField])
However, if we don't know what the starting day is we'll have to construct a date we can start with first, so you can do something like this:
SELECT DATEADD(mm, 1,
CAST(
CAST(DATEPART(mm, [DateField]) AS VARCHAR) +
'/15/' +
CAST(DATEPART(yy, [DateField]) AS VARCHAR)
AS DATETIME))
From Aaron - here is how I would write this to avoid shorthand, regional issues and improper casting:
SELECT DATEADD(MONTH, 1, CONVERT(CHAR(6), DateColumn, 112) + '15')
FROM ...

Resources