How Can I merge two DateTime parts (Hour, Minute, Second) in SQL? - sql

I have two datetime field in my Table like these:
Transaction_RequestDateTime
Transaction_ResponseDateTime
I assigned value to this field in this way : (in C# win form program)
Transaction_RequestDateTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ff");
Transaction_ResponseDateTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss:ff");
as u see in above code, I used hh in responsing time, instead of HH. so when I want to get Datediff in SQL, It wont give me right different value.
for example the values are like this :
Transaction_RequestDateTime = 2015-02-13 21:28:53.390
Transaction_ResponseDateTime = 2015-02-13 09:28:54.500
as you can see, the difference is just in Minutes, our Second.
so, my question is this:
How can I change Transaction_ResponseDateTime values, as the hour part be like Transaction_ResponseDateTime 's hour?
for example I want to update these 2 records like this :
Transaction_RequestDateTime = 2015-02-13 21:28:53.390
Transaction_ResponseDateTime = 2015-02-13 21:28:54.500 // 21 instead of 09
Thanks for any helping...

You can use cast the date into varchar datatype then use left and right part.
Like this
Declare #Date1 DateTime
SET #Date1 = '2015-01-01 15:45:00'
Declare #Date2 DateTime
SET #Date2 = '2015-12-31 12:00:00'
Declare #Combined DateTime
SET #Combined = Cast(Left(#Date2, 11) + Right(#Date1, 7) As DateTime)
print #Combined
You can also add the time after your sql date like this
SET #Combined = Cast(Left(#Date2, 11) + ' 09:00:00' As DateTime)
print #Combined
EDITED:
If you want to get a part of the date object in SQL then you can use DatePart function to get particular part of date. for example Year, Month, Date, Hour, Minutes and Seconds.
DatePart(expression, dateobjct)
--------------------------------
Year : yy or yyyy
Month : mm or m
Day : dd or d
Weekday : dw
Hour : hh
Minutes : mi or n
Seconds : ss or s
Milli.Sec. : ms
You can use this function like this.
print DatePart(yyyy, #Date1)
--Output will be 2015
SET #Combined = Cast(Left(#Date2, 11) + ' ' + Cast(DatePart(hh, #Date1) As Varchar) + ':00:00' As DateTime)
Select #Combined

Not sure if you are dealing with strings or not, but IF those fields are stored in the table as datetime then simply calculating the difference in hours and adding that difference to the incorrect field will work, like this:
CREATE TABLE Table1
([ID] int identity primary key, [Transaction_RequestDateTime] datetime, [Transaction_ResponseDateTime] datetime)
;
INSERT INTO Table1
([Transaction_RequestDateTime], [Transaction_ResponseDateTime])
VALUES
('2015-02-13 21:28:53', '2015-02-13 09:28:54')
;
update table1
set Transaction_ResponseDateTime =
dateadd(hour,
datepart(hour,Transaction_RequestDateTime)
- datepart(hour,Transaction_ResponseDateTime)
, Transaction_ResponseDateTime)
datepart(hour,Transaction_RequestDateTime) = 19
- datepart(hour,Transaction_ResponseDateTime) = 10
so:
dateadd(hour, (19 - 10) , Transaction_ResponseDateTime)

Related

SQL Column Concatenation whilst keeping the datatype of first column [duplicate]

In an extract I am dealing with, I have 2 datetime columns. One column stores the dates and another the times as shown.
How can I query the table to combine these two fields into 1 column of type datetime?
Dates
2009-03-12 00:00:00.000
2009-03-26 00:00:00.000
2009-03-26 00:00:00.000
Times
1899-12-30 12:30:00.000
1899-12-30 10:00:00.000
1899-12-30 10:00:00.000
You can simply add the two.
if the Time part of your Date column is always zero
and the Date part of your Time column is also always zero (base date: January 1, 1900)
Adding them returns the correct result.
SELECT Combined = MyDate + MyTime FROM MyTable
Rationale (kudos to ErikE/dnolan)
It works like this due to the way the date is stored as two 4-byte
Integers with the left 4-bytes being the date and the right
4-bytes being the time. Its like doing $0001 0000 + $0000 0001 =
$0001 0001
Edit regarding new SQL Server 2008 types
Date and Time are types introduced in SQL Server 2008. If you insist on adding, you can use Combined = CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME)
Edit2 regarding loss of precision in SQL Server 2008 and up (kudos to Martin Smith)
Have a look at How to combine date and time to datetime2 in SQL Server? to prevent loss of precision using SQL Server 2008 and up.
If the time element of your date column and the date element of your time column are both zero then Lieven's answer is what you need. If you can't guarantee that will always be the case then it becomes slightly more complicated:
SELECT DATEADD(day, 0, DATEDIFF(day, 0, your_date_column)) +
DATEADD(day, 0 - DATEDIFF(day, 0, your_time_column), your_time_column)
FROM your_table
This is an alternative solution without any char conversions:
DATEADD(ms, DATEDIFF(ms, '00:00:00', [Time]), CONVERT(DATETIME, [Date]))
You will only get milliseconds accuracy this way, but that would normally be OK. I have tested this in SQL Server 2008.
This worked for me
CAST(Tbl.date as DATETIME) + CAST(Tbl.TimeFrom AS TIME)
(on SQL 2008 R2)
If you're not using SQL Server 2008 (i.e. you only have a DateTime data type), you can use the following (admittedly rough and ready) TSQL to achieve what you want:
DECLARE #DateOnly AS datetime
DECLARE #TimeOnly AS datetime
SET #DateOnly = '07 aug 2009 00:00:00'
SET #TimeOnly = '01 jan 1899 10:11:23'
-- Gives Date Only.
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, #DateOnly))
-- Gives Time Only.
SELECT DATEADD(Day, -DATEDIFF(Day, 0, #TimeOnly), #TimeOnly)
-- Concatenates Date and Time parts.
SELECT
CAST(
DATEADD(dd, 0, DATEDIFF(dd, 0, #DateOnly)) + ' ' +
DATEADD(Day, -DATEDIFF(Day, 0, #TimeOnly), #TimeOnly)
as datetime)
It's rough and ready, but it works!
If both of your fields are datetime then simply adding those will work.
eg:
Declare #d datetime, #t datetime
set #d = '2009-03-12 00:00:00.000';
set #t = '1899-12-30 12:30:00.000';
select #d + #t
If you used Date & Time datatype then just cast the time to datetime
eg:
Declare #d date, #t time
set #d = '2009-03-12';
set #t = '12:30:00.000';
select #d + cast(#t as datetime)
This was my solution which ignores the date value of the time column
CAST(Tbl.date as DATETIME) + CAST(CAST(Tbl.TimeFrom AS TIME) as DATETIME)
Hope this helps others
Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.
Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103)
Convert both field into DATETIME :
SELECT CAST(#DateField as DATETIME) + CAST(#TimeField AS DATETIME)
and if you're using Getdate() use this first:
DECLARE #FechaActual DATETIME = CONVERT(DATE, GETDATE());
SELECT CAST(#FechaActual as DATETIME) + CAST(#HoraInicioTurno AS DATETIME)
I had many errors as stated above so I did it like this
try_parse(concat(convert(date,Arrival_date),' ',arrival_time) as datetime) AS ArrivalDateTime
It worked for me.
Finding this works for two dates where you want time from one and date from the other:
declare #Time as datetime = '2021-11-19 12:34'
declare #Date as datetime = '2021-10-10'
SELECT #time + datediff(day, #Time, #Date)
DECLARE #Dates table ([Date] datetime);
DECLARE #Times table ([Time] datetime);
INSERT INTO #Dates VALUES('2009-03-12 00:00:00.000');
INSERT INTO #Dates VALUES('2009-03-26 00:00:00.000');
INSERT INTO #Dates VALUES('2009-03-30 00:00:00.000');
INSERT INTO #Times VALUES('1899-12-30 12:30:00.000');
INSERT INTO #Times VALUES('1899-12-30 10:00:00.000');
INSERT INTO #Times VALUES('1899-12-30 10:00:00.000');
WITH Dates (ID, [Date])
AS (
SELECT ROW_NUMBER() OVER (ORDER BY [Date]), [Date] FROM #Dates
), Times (ID, [Time])
AS (
SELECT ROW_NUMBER() OVER (ORDER BY [Time]), [Time] FROM #Times
)
SELECT Dates.[Date] + Times.[Time] FROM Dates
JOIN Times ON Times.ID = Dates.ID
Prints:
2009-03-12 10:00:00.000
2009-03-26 10:00:00.000
2009-03-30 12:30:00.000
To combine date from a datetime column and time from another datetime column this is the best fastest solution for you:
select cast(cast(DateColumn as date) as datetime) + cast(TimeColumn as datetime) from YourTable
SELECT CAST(CAST(#DateField As Date) As DateTime) + CAST(CAST(#TimeField As Time) As DateTime)
Another way is to use CONCATand CAST, be aware, that you need to use DATETIME2(x) to make it work. You can set x to anything between 0-7 7 meaning no precision loss.
DECLARE #date date = '2018-03-12'
DECLARE #time time = '07:00:00.0000000'
SELECT CAST(CONCAT(#date, ' ', #time) AS DATETIME2(7))
Returns 2018-03-12 07:00:00.0000000
Tested on SQL Server 14
simply concatenate both , but cast them first as below
select cast(concat(Cast(DateField as varchar), ' ', Cast(TimeField as varchar)) as datetime) as DateWithTime from TableName;
select s.SalesID from SalesTbl s
where cast(cast(s.SaleDate as date) as datetime) + cast(cast(s.SaleCreatedDate as time) as datetime) between #FromDate and #ToDate
The existing answers do not address the datetime2 datatype so I will add mine:
Assuming that you want to add a time value to a datetime2 value where:
The datetime2 value could contain non-zero time component and/or fractional seconds
The time value could contain the value 23:59:59.9999999 which is 86,399.9999999 seconds, 86,399,999,999.9 microseconds or 86,399,999,999,900 nanoseconds¹
Due to the limitations of dateadd function¹ you must add them in two steps:
Convert the time value to seconds and use dateadd(second, ...)
Extract the nanoseconds from the time value and use dateadd(nanosecond, ...) to add them to the date calculated above
declare #dv datetime2 = '2000-01-01 12:34:56.7890123';
declare #tv time = '23:59:59.9999999';
select dateadd(
nanosecond,
datepart(nanosecond, #tv),
dateadd(
second,
datepart(hour, #tv) * 60 * 60 + datepart(minute, #tv) * 60 + datepart(second, #tv),
#dv
)
);
-- 2000-01-02 12:34:56.7890122
¹ Nanosecond values might not fit in int datatype which dateadd function expects.
SELECT CAST(your_date_column AS date) + CAST(your_time_column AS datetime) FROM your_table
Works like a charm
I ran into similar situation where I had to merge Date and Time fields to DateTime field. None of the above mentioned solution work, specially adding two fields as the data type for addition of these 2 fields is not same.
I created below solution, where I added hour and then minute part to the date. This worked beautifully for me. Please check it out and do let me know if you get into any issues.
;with tbl
as
(
select StatusTime = '12/30/1899 5:17:00 PM', StatusDate = '7/24/2019 12:00:00 AM'
)
select DATEADD(MI, DATEPART(MINUTE,CAST(tbl.StatusTime AS TIME)),DATEADD(HH, DATEPART(HOUR,CAST(tbl.StatusTime AS TIME)), CAST(tbl.StatusDate as DATETIME)))
from tbl
Result: 2019-07-24 17:17:00.000

Update date only in SQL Server [duplicate]

This question already has an answer here:
T-SQL: How to update just date part of datetime field?
(1 answer)
Closed 9 years ago.
I have this row in my database table with a value of 1/5/2013 5:50:00 PM, and I want to update only the date part. Time should be same without any change, need to change only the date in this record.
I have tried the update statement but it change the time as well..but I can do a
UPDATE table1
SET date = '1/10/2013 5:50:00 PM'
WHERE id =1
This not what I'm looking for, different id's have different times, so just need to update the date keeping the time in that record same.
Please give feedback.
Thank you
You can do it this way if you're using SQL Server 2008 or higher
UPDATE table1
SET [date] = cast('1/10/2013' as datetime) + cast(cast([date] as time) as datetime)
WHERE id =1
If you're using SQL Server 2005 or below, you there's no time data type, so you have to do:
UPDATE table1
SET [date] = cast('1/10/2013' as datetime) + ([date] - DATEADD(dd, 0, DATEDIFF(dd, 0, [date])))
WHERE id =1
UPDATE table1
SET date = DATEADD(dd,5,date)-- 5 is the number of days
FROM table1
WHERE id =1
Not the most elegant, but should work. Idea is to extract hours,minutes and seconds from target row and hard code other parts.
update table1 set date = DATEADD(second, DATEPART(second, date), DATEADD(minute, DATEPART(minute, date), DATEADD(hour, DATEPART(hour,date), '2013-01-10')));
Though a bit hackish in appearance, this will do the trick if you ONLY want to change the date part with an arbitary value, and not touch the time part at all:
update table1 set date= '06-dec-2013 ' + cast(datepart(HOUR,date) as varchar(2)) + ':' +
cast(datepart(MINUTE,date) as varchar(2)) + ':' +
cast(DATEPART(SECOND, date) as varchar(2)) + ' ' +
CASE WHEN DATEPART(HOUR, date) < 12 THEN 'AM' ELSE 'PM' END as datetime
where id=1
Replace '06-dec-2013' with the date value you want to replace with.
create table t
(
col1 datetime
)
Insert Into t
values ('1/5/2013 5:50:00 PM')
declare #newDate datetime
set #newDate = '1/10/2013'
update t
Set col1 = convert(datetime,DateAdd(day, DateDiff(day, col1, #newDate), Col1),101)
sql-fiddle demo
Here's the query you want:
declare #TargetDate datetime
set #TargetDate = '20131001' --1st October 2013
update table1 set [date] = DATEADD(day,DATEDIFF(day,[date],#TargetDate),[date])
where id = 1
And here's a complete script to demonstrate it:
declare #t table (dt datetime not null)
insert into #t (dt) values
('2001-01-01T10:53:44.993'),('2012-06-18T15:33:33.333')
declare #TargetDate datetime
set #TargetDate = '20131001' --1st October 2013
update #t set dt = DATEADD(day,DATEDIFF(day,dt,#TargetDate),dt)
select * from #t
Results:
dt
-----------------------
2013-10-01 10:53:44.993
2013-10-01 15:33:33.333
This works by using DATEDIFF to work out how many days different the target date is from each date stored in the table (with appropriate signage) and then adding that difference back onto the date - having the effect of adjusting the date portions of the stored values whilst not affecting the time.

i have start date&time and end date&time...i need the difference between start and end

I have start date&time and end date&time. I need the difference between these two and when end date&time is null then i need the differ between start date&time and current date&time...... Thanks in advance.
select pwr.ondate ONDATE,pwr.offdate OFFDATE,mp.process FROMPROCESS,
(select mp.process from mas_process mp where pwr.protoid=mp.p_id) TOPROCESS,
USEDHOURS = case when pwr.offdate is null then
datediff(HH,pwr.ondate,getdate()) else
datediff(d,pwr.ondate,pwr.offdate)
end
from powerreport pwr
inner join mas_process mp on pwr.proid=mp.p_id
If you want to express the difference between two datetimes in the format hour:minute you can obtain the minute portion by first calculating the total number of minutes between the two datetimes using datediff like you were: datediff(MI, startDate, endDate) and then calculating modulos 60 against the results of the datediff.
The modulo operator in SQL Server is % so the expression for this would be datediff(MI, startDate, endDate) % 60
I would suggest creating a local variable and populating it with the results of a GETDATE() call so all rows in your results are calculated using the exact same datetime for cases when the end date for a particular record is null. Additionally you can simplify the query if you use IsNull() against the end date and have it return current time if the end date is null.
If you put all three of those together you would have a query that looks something like the following to calculate the difference for all records in your powerreport table:
DECLARE #currentTime AS DATETIME;
SET #currentTime = GETDATE();
SELECT *,
USEDHOURS =
CAST (datediff(HH, pwr.ondate,
IsNull(pwr.offdate, #currentTime)) AS VARCHAR) + ':' +
CAST (datediff(MI, pwr.ondate,
IsNull(pwr.offdate, #currentTime)) % 60 AS VARCHAR)
FROM powerreport AS pwr;
Here is a SQL Fiddle showing this in action: http://sqlfiddle.com/#!3/e47af/1
And if you plugged this into your original query the result should be something like the following:
DECLARE #currentTime AS DATETIME;
SET #currentTime = GETDATE();
SELECT pwr.ondate AS ONDATE,
pwr.offdate AS OFFDATE,
mp.process AS FROMPROCESS,
(SELECT mp.process
FROM mas_process AS mp
WHERE pwr.protoid = mp.p_id) AS TOPROCESS,
USEDHOURS =
CAST (datediff(HH, pwr.ondate,
IsNull(pwr.offdate, #currentTime)) AS VARCHAR) + ':' +
CAST (datediff(MI, pwr.ondate,
IsNull(pwr.offdate, #currentTime)) % 60 AS VARCHAR)
FROM powerreport AS pwr
INNER JOIN
mas_process AS mp
ON pwr.proid = mp.p_id;

Best way to compare dates without time in SQL Server

select * from sampleTable
where CONVERT(VARCHAR(20),DateCreated,101)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),101)
I want to compare date without time
Is above query is ok? or other better solution you suggest
I am using SQL Server 2005
Date saved in UTC format on server
Users against this data belongs different timezone
Simple Cast to Date will resolve the problem.
DECLARE #Date datetime = '04/01/2016 12:01:31'
DECLARE #Date2 datetime = '04/01/2016'
SELECT CAST(#Date as date)
SELECT CASE When (CAST(#Date as date) = CAST(#Date2 as date)) Then 1 Else 0 End
Don't use convert - that involves strings for no reason. A trick is that a datetime is actually a numeric, and the days is the integer part (time is the decimal fraction); hence the day is the FLOOR of the value: this is then just math, not strings - much faster
declare #when datetime = GETUTCDATE()
select #when -- date + time
declare #day datetime = CAST(FLOOR(CAST(#when as float)) as datetime)
select #day -- date only
In your case, no need to convert back to datetime; and using a range allows the most efficent comparisons (especially if indexed):
declare #when datetime = 'Feb 15 2012 7:00:00:000PM'
declare #min datetime = FLOOR(CAST(#when as float))
declare #max datetime = DATEADD(day, 1, #min)
select * from sampleTable where DateCreated >= #min and DateCreated < #max
SELECT .......
FROM ........
WHERE
CAST(#DATETIMEVALUE1 as DATE) = CAST(#DATETIMEVALUE2 as DATE)
The disadvantage is that you are casting the filter column.
If there is an index on the filter column, then, since you are casting, the SQL engine can no longer use indexes to filter the date more efficiently.
Description
Don't convert your Date to a varchar and compare because string comparisson is not fast.
It is much faster if you use >= and < to filter your DateCreated column.
If you have no parameter (like in your sample, a string) you should use the ISO Format <Year><Month><Day>.
Sample
According to your sample
DECLARE #startDate DateTime
DECLARE #endDate DateTime
SET #startDate = '20120215'
SET #endDate = DATEADD(d,1,#startDate)
SELECT * FROM sampleTable
WHERE DateCreated >= #startDate AND DateCreated < #endDate
More Information
MSDN - DATEADD (Transact-SQL)
Use 112 CONVERT's format
select *
from sampleTable
where
CONVERT(VARCHAR(20),DateCreated,112)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),112)
or
if your sql server version 2008+ use DATE type
select * from sampleTable
where CONVERT(DATE,DateCreated)
= CONVERT(DATE,CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME))
declare #DateToday Date= '2019-10-1';
print #DateToday;
print Abs(datediff(day, #DateToday,CAST('oct 1 2019 7:00:00:000PM' AS DATETIME))) < 3
this is compare whin 3 days.
i test this on SQL Server 2014, it works.
select * from sampleTable
where date_created ='20120215'
This will also compare your column with the particular date
without taking time into account

How to combine date from one field with time from another field - MS SQL Server

In an extract I am dealing with, I have 2 datetime columns. One column stores the dates and another the times as shown.
How can I query the table to combine these two fields into 1 column of type datetime?
Dates
2009-03-12 00:00:00.000
2009-03-26 00:00:00.000
2009-03-26 00:00:00.000
Times
1899-12-30 12:30:00.000
1899-12-30 10:00:00.000
1899-12-30 10:00:00.000
You can simply add the two.
if the Time part of your Date column is always zero
and the Date part of your Time column is also always zero (base date: January 1, 1900)
Adding them returns the correct result.
SELECT Combined = MyDate + MyTime FROM MyTable
Rationale (kudos to ErikE/dnolan)
It works like this due to the way the date is stored as two 4-byte
Integers with the left 4-bytes being the date and the right
4-bytes being the time. Its like doing $0001 0000 + $0000 0001 =
$0001 0001
Edit regarding new SQL Server 2008 types
Date and Time are types introduced in SQL Server 2008. If you insist on adding, you can use Combined = CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME)
Edit2 regarding loss of precision in SQL Server 2008 and up (kudos to Martin Smith)
Have a look at How to combine date and time to datetime2 in SQL Server? to prevent loss of precision using SQL Server 2008 and up.
If the time element of your date column and the date element of your time column are both zero then Lieven's answer is what you need. If you can't guarantee that will always be the case then it becomes slightly more complicated:
SELECT DATEADD(day, 0, DATEDIFF(day, 0, your_date_column)) +
DATEADD(day, 0 - DATEDIFF(day, 0, your_time_column), your_time_column)
FROM your_table
This is an alternative solution without any char conversions:
DATEADD(ms, DATEDIFF(ms, '00:00:00', [Time]), CONVERT(DATETIME, [Date]))
You will only get milliseconds accuracy this way, but that would normally be OK. I have tested this in SQL Server 2008.
This worked for me
CAST(Tbl.date as DATETIME) + CAST(Tbl.TimeFrom AS TIME)
(on SQL 2008 R2)
If you're not using SQL Server 2008 (i.e. you only have a DateTime data type), you can use the following (admittedly rough and ready) TSQL to achieve what you want:
DECLARE #DateOnly AS datetime
DECLARE #TimeOnly AS datetime
SET #DateOnly = '07 aug 2009 00:00:00'
SET #TimeOnly = '01 jan 1899 10:11:23'
-- Gives Date Only.
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, #DateOnly))
-- Gives Time Only.
SELECT DATEADD(Day, -DATEDIFF(Day, 0, #TimeOnly), #TimeOnly)
-- Concatenates Date and Time parts.
SELECT
CAST(
DATEADD(dd, 0, DATEDIFF(dd, 0, #DateOnly)) + ' ' +
DATEADD(Day, -DATEDIFF(Day, 0, #TimeOnly), #TimeOnly)
as datetime)
It's rough and ready, but it works!
If both of your fields are datetime then simply adding those will work.
eg:
Declare #d datetime, #t datetime
set #d = '2009-03-12 00:00:00.000';
set #t = '1899-12-30 12:30:00.000';
select #d + #t
If you used Date & Time datatype then just cast the time to datetime
eg:
Declare #d date, #t time
set #d = '2009-03-12';
set #t = '12:30:00.000';
select #d + cast(#t as datetime)
This was my solution which ignores the date value of the time column
CAST(Tbl.date as DATETIME) + CAST(CAST(Tbl.TimeFrom AS TIME) as DATETIME)
Hope this helps others
Convert the first date stored in a datetime field to a string, then convert the time stored in a datetime field to string, append the two and convert back to a datetime field all using known conversion formats.
Convert(datetime, Convert(char(10), MYDATETIMEFIELD, 103) + ' ' + Convert(char(8), MYTIMEFIELD, 108), 103)
Convert both field into DATETIME :
SELECT CAST(#DateField as DATETIME) + CAST(#TimeField AS DATETIME)
and if you're using Getdate() use this first:
DECLARE #FechaActual DATETIME = CONVERT(DATE, GETDATE());
SELECT CAST(#FechaActual as DATETIME) + CAST(#HoraInicioTurno AS DATETIME)
I had many errors as stated above so I did it like this
try_parse(concat(convert(date,Arrival_date),' ',arrival_time) as datetime) AS ArrivalDateTime
It worked for me.
Finding this works for two dates where you want time from one and date from the other:
declare #Time as datetime = '2021-11-19 12:34'
declare #Date as datetime = '2021-10-10'
SELECT #time + datediff(day, #Time, #Date)
DECLARE #Dates table ([Date] datetime);
DECLARE #Times table ([Time] datetime);
INSERT INTO #Dates VALUES('2009-03-12 00:00:00.000');
INSERT INTO #Dates VALUES('2009-03-26 00:00:00.000');
INSERT INTO #Dates VALUES('2009-03-30 00:00:00.000');
INSERT INTO #Times VALUES('1899-12-30 12:30:00.000');
INSERT INTO #Times VALUES('1899-12-30 10:00:00.000');
INSERT INTO #Times VALUES('1899-12-30 10:00:00.000');
WITH Dates (ID, [Date])
AS (
SELECT ROW_NUMBER() OVER (ORDER BY [Date]), [Date] FROM #Dates
), Times (ID, [Time])
AS (
SELECT ROW_NUMBER() OVER (ORDER BY [Time]), [Time] FROM #Times
)
SELECT Dates.[Date] + Times.[Time] FROM Dates
JOIN Times ON Times.ID = Dates.ID
Prints:
2009-03-12 10:00:00.000
2009-03-26 10:00:00.000
2009-03-30 12:30:00.000
To combine date from a datetime column and time from another datetime column this is the best fastest solution for you:
select cast(cast(DateColumn as date) as datetime) + cast(TimeColumn as datetime) from YourTable
SELECT CAST(CAST(#DateField As Date) As DateTime) + CAST(CAST(#TimeField As Time) As DateTime)
Another way is to use CONCATand CAST, be aware, that you need to use DATETIME2(x) to make it work. You can set x to anything between 0-7 7 meaning no precision loss.
DECLARE #date date = '2018-03-12'
DECLARE #time time = '07:00:00.0000000'
SELECT CAST(CONCAT(#date, ' ', #time) AS DATETIME2(7))
Returns 2018-03-12 07:00:00.0000000
Tested on SQL Server 14
simply concatenate both , but cast them first as below
select cast(concat(Cast(DateField as varchar), ' ', Cast(TimeField as varchar)) as datetime) as DateWithTime from TableName;
select s.SalesID from SalesTbl s
where cast(cast(s.SaleDate as date) as datetime) + cast(cast(s.SaleCreatedDate as time) as datetime) between #FromDate and #ToDate
The existing answers do not address the datetime2 datatype so I will add mine:
Assuming that you want to add a time value to a datetime2 value where:
The datetime2 value could contain non-zero time component and/or fractional seconds
The time value could contain the value 23:59:59.9999999 which is 86,399.9999999 seconds, 86,399,999,999.9 microseconds or 86,399,999,999,900 nanoseconds¹
Due to the limitations of dateadd function¹ you must add them in two steps:
Convert the time value to seconds and use dateadd(second, ...)
Extract the nanoseconds from the time value and use dateadd(nanosecond, ...) to add them to the date calculated above
declare #dv datetime2 = '2000-01-01 12:34:56.7890123';
declare #tv time = '23:59:59.9999999';
select dateadd(
nanosecond,
datepart(nanosecond, #tv),
dateadd(
second,
datepart(hour, #tv) * 60 * 60 + datepart(minute, #tv) * 60 + datepart(second, #tv),
#dv
)
);
-- 2000-01-02 12:34:56.7890122
¹ Nanosecond values might not fit in int datatype which dateadd function expects.
SELECT CAST(your_date_column AS date) + CAST(your_time_column AS datetime) FROM your_table
Works like a charm
I ran into similar situation where I had to merge Date and Time fields to DateTime field. None of the above mentioned solution work, specially adding two fields as the data type for addition of these 2 fields is not same.
I created below solution, where I added hour and then minute part to the date. This worked beautifully for me. Please check it out and do let me know if you get into any issues.
;with tbl
as
(
select StatusTime = '12/30/1899 5:17:00 PM', StatusDate = '7/24/2019 12:00:00 AM'
)
select DATEADD(MI, DATEPART(MINUTE,CAST(tbl.StatusTime AS TIME)),DATEADD(HH, DATEPART(HOUR,CAST(tbl.StatusTime AS TIME)), CAST(tbl.StatusDate as DATETIME)))
from tbl
Result: 2019-07-24 17:17:00.000