Convert varchar to datetime and add seconds - sql-server

I have two columns startDate (160812 - year, month, day) and startTime (112345 - hour, mimutes, seconts) with a varchar datatype my target is concatenate them and convert them into datetime. And I should added to them other column (duration - int)
I tried something like this:
WITH [A] AS
(
SELECT (startDate + startTime) AS time1
FROM [Date]
)
SELECT
CONVERT(datetime, A.time1, 20)
FROM
[A]
however I get an error message:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Any better ideas to try?

I think you want something like this:
select (convert(datetime, startDate, 12) +
convert(time, stuff(stuff(startTime, 5, 0, ':'), 3, 0, ':')))
) as dt

Related

Issue with chosing between dates in SQL Server, error msg241

I'm trying to query this:
SELECT *
FROM dbo.rate_all_ports
WHERE start_date <= CONVERT(DATE, GETDATE())
AND stop_date >= CONVERT(DATE, GETDATE())
But it doesn't work. I get the error:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
In the table I'm querying from the dates are formatted like YYYY-MM-DD so I don't know where the error.
If I query like this:
SELECT *
FROM dbo.rate_all_ports
WHERE start_date <= '2022-12-02'
AND stop_date >= '2022-12-02'
it works.
And if query SELECT CONVERT(DATE, GETDATE()), I get 2022-12-02.

Convert column of type Float to Date in sql-server

My dates stored in a float column, I tried to change it to timestamp with no luck,
now I want to calculate the age from that field, I have tried all sorts of combinations using CONVERT and CAST functions, but it does not seem to work.
DoB
-434419200000
606960000000
1332806400000
1395878400000
-87350400000
890956800000
I tried:
SELECT DATEADD(ss, dob, '19700101')
from tbl
//Result
Error overflow .. arithmetique for type int, value= -434419200000.000000
SELECT DATEADD(ss, CONVERT(bigint, dob, 101), '19700101')
from tbl
//Result
Error while conversion from expression to type int.
UPDATE
NOTE that the data here is from milliseconds from the date"1970/1/1 00:00:00"
Thank you.
As I mention in the comments, this is a combined duplicate of the questions converting Epoch timestamp to sql server(human readable format) and How to calculate age (in years) based on Date of Birth and getDate().
Sample data:
CREATE TABLE dbo.YourTable (DoB float);
INSERT INTO dbo.YourTable (DoB)
VALUES (-434419200000),
(606960000000),
(1332806400000),
(1395878400000),
(-87350400000),
(890956800000);
Then using the first link we get:
SELECT DATEADD(SECOND, DoB / 1000,'19700101') --As yours is milliseconds, not seconds.
FROM dbo.YourTable;
Then we can use the answer from the second link:
SELECT YT.DoB,
V.DateOfBirth,
CONVERT(int,DATEDIFF(yy, V.DateOfBirth, GETDATE()) +
CASE WHEN GETDATE() >= DATEFROMPARTS(DATEPART(yyyy, GETDATE()), DATEPART(m, V.DateOfBirth), DATEPART(d, V.DateOfBirth)) THEN (1.0 * DATEDIFF(DAY, DATEFROMPARTS(DATEPART(yyyy, GETDATE()), DATEPART(m, V.DateOfBirth), DATEPART(d, V.DateOfBirth)), GETDATE()) / DATEDIFF(DAY, DATEFROMPARTS(DATEPART(yyyy, GETDATE()), 1, 1), DATEFROMPARTS(DATEPART(yyyy, GETDATE()) + 1, 1, 1)))
ELSE -1 * (-1.0 * DATEDIFF(DAY, DATEFROMPARTS(DATEPART(yyyy, GETDATE()), DATEPART(m, V.DateOfBirth), DATEPART(d, V.DateOfBirth)), GETDATE()) / DATEDIFF(DAY, DATEFROMPARTS(DATEPART(yyyy, GETDATE()), 1, 1), DATEFROMPARTS(DATEPART(yyyy, GETDATE()) + 1, 1, 1)))
END) AS Age
FROM dbo.YourTable YT
CROSS APPLY (VALUES (DATEADD(SECOND, YT.DoB / 1000, '19700101'))) V (DateOfBirth);
If this answer helps, I suggest upvoting the answers that I link above as well, as this is a combination of those said answers.
The correct datatype would be bigint instead of float. In fact I would rather import the timestamps in a date column.
Having said that, divide the number by 1000 to avoid overflow error:
select dateadd(second, -434419200000e0 / 1000, '1970-01-01')
-- 1956-03-27 00:00:00.000

How to get all data which time is in range to next 2 hours from current time in SQL

I have a table tblSMS with a datetime and time column (and some other columns).
I get all reminder within next 2 hours on dashboard so I want to get data from table where datetime is today and time is within the next 2 hours.
I used this stored procedure, but it is not working:
select *
from tblSMS
where
SMSTime >= (SELECT Convert(varchar(5), GetDate(), 108))
and (SMSTime <= (SELECT Convert(varchar(5), (Select dateadd (hour, 2, getdate())), 108)))
and Convert(varchar(10), SMSDate, 110) = Convert(varchar(10), GETDATE(), 110)
Thanks
No need to use time column if you are storing in proper datetime format. It's better to make comparisons in datetime format. Otherwise you may have troubles if next 2 hours falls on the next day.
select *
from tblSMS
where
SMSDate between getdate() and dateadd(hh, 2, getdate())
Combine two columns to get datetime if you are storing SMSDate as a date
select *
from tblSMS
where
SMSDate + cast(SMSTime as datetime) between getdate() and dateadd(hh, 2, getdate())

Converting int to Date

How to convert to date in sql Server when i have data type int in my database?
For Example :
5th day in 4th week of 10th month in 2016
Use can DATEFROMPARTS function
Select DATEFROMPARTS(Year,Month,Day) as Dates
From yourtable
If you are using less then 2012 then
Select cast(cast(year as char(4))+'-'+cast(month as varchar(2))+'-'+cast(day as varchar(2)) as date) as dates
From yourtable
This is a truly horrible way to store date information. It is a serious pain to work with and nearly impossible to validate. You really should use the native date datatype for this type of thing.
This produced the desired output for your sample. I think this is what you are looking for.
create table #SomeDate
(
MyDay int
, MyWeek int
, MyMonth int
, MyYear int
)
insert #SomeDate
select 5, 4, 10, 2016
select dateadd(day, s.MyDay + 1, dateadd(week, s.MyWeek - 1, dateadd(month, s.MyMonth - 1, dateadd(year, s.MyYear - 1900, 0))))
from #SomeDate s
drop table #SomeDate

Construct DateTime using today's date at a specific time

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.

Resources