I'm trying to add custom time to datetime in SQL Server 2008 R2.
Following is what I've tried.
SELECT DATEADD(hh, 03, DATEADD(mi, 30, DATEADD(ss, 00, DATEDIFF(dd, 0,GETDATE())))) as Customtime
Using the above query, I'm able to achieve it.
But is there any shorthand method already available to add custom time to datetime?
This question is related to
sql
sql-server-2008
datetime
Or try an alternate method using Time datatype:
DECLARE @MyTime TIME = '03:30:00', @MyDay DATETIME = CAST(GETDATE() AS DATE)
SELECT @MyDay+@MyTime
Try this
SELECT DATEADD(MINUTE,HOW_MANY_MINUTES,TO_WHICH_TIME)
Here MINUTE
is constant which indicates er are going to add/subtract minutes from TO_WHICH_TIME
specifier. HOW_MANY_MINUTES
is the interval by which we need to add minutes, if it is specified negative, time will be subtracted, else would be added to the TO_WHICH_TIME
specifier and TO_WHICH_TIME
is the original time to which you are adding MINUTE
.
Hope this helps.
Try this:
SELECT DATEDIFF(dd, 0,GETDATE()) + CONVERT(DATETIME,'03:30:00.000')
For me, this code looks more explicit:
CAST(@SomeDate AS datetime) + CAST(@SomeTime AS datetime)
You can do:
SELECT GETDATE()+'03:30:00'
Start Day Time : SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '00:00:00')
End Day Time : SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '23:59:59')
The following is simple and works on SQL Server 2008 (SP3) and up:
PRINT @@VERSION
PRINT GETDATE()
PRINT GETDATE() + '01:00:00'
PRINT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE()))) + '01:00:00'
With output:
Microsoft SQL Server 2008 (SP3) - 10.0.5500.0 (X64)
Mar 15 2017 6:17PM
Mar 15 2017 7:17PM
Mar 15 2017 1:00AM
DECLARE @DDate date -- To store the current date
DECLARE @DTime time -- To store the current time
DECLARE @DateTime datetime -- To store the result of the concatenation
;
SET @DDate = GETDATE() -- Getting the current date
SET @DTime = GETDATE() -- Getting the current time
SET @DateTime = CONVERT(datetime, CONVERT(varchar(19), LTRIM(@DDate) + ' ' + LTRIM(@DTime) ));
;
/*
1. LTRIM the date and time do an automatic conversion of both types to string.
2. The inside CONVERT to varchar(19) is needed, because you cannot do a direct conversion to datetime
3. Once the inside conversion is done, the second do the final conversion to datetime.
*/
-- The following select shows the initial variables and the result of the concatenation
SELECT @DDate, @DTime, @DateTime
Source: Stackoverflow.com