convert string to both date and time - sql

I have a data where date and time comes up in yyyymmdd_time (20161012_1528) format.
I want to convert it to date time in SQL Server DB as 2016-10-12 15:28:00:00
is there any straight forward way to do this.or have to create a custom function?

Declare #String varchar(25) = '20161012_1528'
Select cast(left(#String,8)+' '+Stuff(right(#String,4),3,0,':') as datetime)
Or
Select cast(Stuff(Replace(#String,'_',' '),12,0,':') as datetime)
Returns
2016-10-12 15:28:00.000

Please try following method,
It requires a few datetime and convertion functions to be used
declare #dt datetime
declare #str varchar(40) = '20161012_1528'
select #dt =
DATEADD(MI, CAST(right(#str,2) as int),
DATEADD(hh, cast(SUBSTRING(#str,10,2) as int),
CONVERT(datetime, left(#str,8))
)
)
select #dt

The closest I could find was datetime format 112 which does not account for the "_hhmm". I would highly recommend just placing the convert into your T-SQL as the optimizer does not handle UDFs very well.
The T-SQL looks like:
DECLARE #datetimestring nvarchar(max) = '20161012_1528'
SELECT
dateadd(
minute,convert(
int,substring(
#datetimestring,charindex(
'_',#datetimestring
)+3,2
)
),dateadd(
hour,convert(
int,substring(
#datetimestring,charindex(
'_',#datetimestring
)+1,2
)
),convert(
datetime, substring(
#datetimestring,0,charindex(
'_',#datetimestring
)
), 112
)
)
)
The other option is to format the string to the expected date format which is shorter.
SELECT
convert(
datetime,replace(
stuff(
stuff(
stuff(
#datetimestring,5,0,'-'
),8,0,'-'
),14,0,':'
),'_',' '
)
)

Related

How to convert round number to data and time format

Two Column in table tblpress
Date Time
20160307 120949
20160307 133427
Need to be select below the format:
07-03-2016 12:09:49
07-03-2016 13:34 27
or
03-March-2016 12:09: 49 PM
03-March-2016 01:34: 27 PM
You can try below
select format(cast([Date] as date),'dd-MMMM-yyyy') as [Date],
TIMEFROMPARTS(LEFT([Time],2), SUBSTRING([Time],3,2), RIGHT([Time],2), 0,0) as [Time]
I think CAST/CONVERT will help you:
SELECT
CAST('20160307' AS date),
CAST(STUFF(STUFF('120949',3,0,':'),6,0,':') AS time)
And convert for out:
SELECT
CONVERT(varchar(20),NormalDate,105) OutDate, -- Italian style
CONVERT(varchar(20),NormalTime,108) OutTime -- hh:mi:ss
FROM
(
SELECT
CAST([Date] AS date) NormalDate,
CAST(STUFF(STUFF([Time],3,0,':'),6,0,':') AS time) NormalTime
FROM YourTable
) q
CAST and CONVERT (Transact-SQL)
And you can use FORMAT (Transact-SQL)
SELECT
FORMAT(GETDATE(),'dd-MM-yyyy'),
FORMAT(GETDATE(),'HH:mm:ss')
Best way to do it is to create a function :
create FUNCTION [dbo].[udfGetDateTimeFromInteger]
(
#intDate int,
#intTime int
)
RETURNS datetime
AS BEGIN
-- Declare the return variable here
DECLARE #DT_datetime datetime = NULL,
#str_date varchar(11),
#str_time varchar(8)
if(#intDate is not null and #intDate > 0)
begin
select #str_date = CAST( cast(#intDate as varchar(8)) AS date)
if #intTime=0
select #str_time ='000000'
else
select #str_time = right('0'+CONVERT(varchar(11),#intTime),6)
select #str_time =
SUBSTRING(#str_time,1,2)+':'+SUBSTRING(#str_time,3,2)+':'+SUBSTRING(#str_time,5,2)
select #DT_datetime = CAST(#str_date+' '+#str_time as datetime)
end
-- Return the result of the function
RETURN #DT_datetime
END
and then call it in select like :
declare #next_run_date int, #next_run_time int
select #next_run_date = 20160307
select #next_run_time = 130949
SELECT #next_run_date inputdate,
#next_run_time inputtime,
dbo.udfGetDateTimeFromInteger(#next_run_date, #next_run_time) outputdatetime
Output will be like :
inputdate inputtime outputdatetime
20160307 130949 2016-03-07 13:09:49.000
You said those are numbers, right? You can use datetimefromparts (or datetime2fromparts). ie:
select
datetimefromparts(
[date]/10000,
[date]%10000/100,
[date]%100,
[time]/10000,
[time]%10000/100,
[time]%100,0)
from tblpress;
DB Fiddle demo
Note that naming fields like that and also storing date and time like that is a bad idea.
I later noticed it was char fields:
select
cast([date] as datetime) +
cast(stuff(stuff([time],5,0,':'),3,0,':') as datetime)
from tblpress;

sql server convert datetime failed

I want to convert this time_stamp column (nvarchar50) into datetime column in SQL server. the value of time_stamp is "2018-02-16 13:30:27+09:00".
I don't know which datetime code should I use to convert it. Can you help?
This is what I tried:
select convert(datetime,time_stamp, 110) from table;
select convert(datetime,time_stamp, 120) from table;
It is failing because of the timezone embedded in the string. However, it will work if you remove the timezone using string function such as LEFT.
SELECT CONVERT(DATETIME, LEFT(time_stamp, 19), 110)
FROM tableName
Here's a Demo.
There is timezone offset in your sample date. If we want to ignore timezone offset then we can use below code -
declare #x nvarchar(50) = '2018-02-16 13:30:27+09:00'
select convert(datetime,convert(datetimeoffset, #x))
Declare #dt NVARCHAR(100) = '2018-02-16 13:30:27+09:00'
select CAST(SWITCHOFFSET(TODATETIMEOFFSET( LEFT(#dt , 19) ,RIGHT(#dt, 6)),0) AS DATETIME)
Returns:
2018-02-16 04:30:27.000

How to add 1 day to current date and have result in format yyyymmdd in SQL Server?

I need to add 1 day to the current date and have the output in the format yyyymmdd.
The code needs to be written on a stored procedure on the sql server.
currently my code is as follows:
DECLARE #dat DATE
select #dat = dateadd(DD, 1, getdate())
SELECT #dat =LEFT(CONVERT(VARCHAR(8), #dat, 112),10)
However, it seems like im doing something wrong as my output on the sql table is in the format yyyy-mm-dd. I need to get rid of the hyphens.
any suggestions guys? thanks in advance.
The issue is that you are assigning it back to a date object. You need to assign it to a varchar.
I did the following in SQL Server 2005:
DECLARE #dat DATETIME
DECLARE #string varchar(8)
SET #dat = GetUtcDate()
select #dat = dateadd(DD, 1, getdate())
SELECT #string =CONVERT(VARCHAR(8), #dat, 112)
PRINT #string
Change the declaration of #dat to a STRING
Try this one -
DECLARE #date VARCHAR(8)
SELECT #date = CONVERT(VARCHAR(8), DATEADD(DAY, 1, GETDATE()), 112)
SELECT #date
select #dat = dateadd(DD, 1, getdate())
DECLARE #datCus varchar(8)
select #datCus=LEFT(CONVERT(VARCHAR(8), #dat, 112),10)
The problem was that i assigned #dat to the insert statements values. However having a varchar variable to handle the converting part solved the problem (in this case #datCus).

T-SQL String to DateTime-conversion

I need to cast string values of the following formats to DateTime:
2042-04
2011-01
Is there an easy way to do this? I've tried CAST AND CONVERT without much luck.
Thanks!
try appending "-01" to the end of it and then doing the cast or convert
declare #S varchar(7)
set #S = '2042-04'
select cast(stuff(#S, 5, 1, '')+'01' as datetime)
YYYYMMDD is a safe format regardless of SET DATEFORMAT. YYYY-MM-DD is not. http://www.sommarskog.se/wishlist.html#YYYYMMDD
SELECT CAST('2011-01-01' AS DATETIME)
SELECT CONVERT(DATE , '2011-01-01')
It seems you need to add a 'day' to the string.
Declare #Table Table
(
ColDateTime Varchar(100)
)
Insert into #Table
Select '2042-04' UNION ALL
Select '2011-01'
Select ColDateTime As VarcharCol,
Cast(
substring(ColDateTime,0,charindex('-',ColDateTime))+substring(ColDateTime,charindex('-',ColDateTime)+1,len(ColDateTime))+'01'
As DateTime) As DateTimeCol
from #Table

How do I create a datetime from a custom format string?

I have datetime values stored in a field as strings. They are stored as strings because that's how they come across the wire and the raw values are used in other places.
For reporting, I want to convert the custom format string (yyyymmddhhmm) to a datetime field in a view. My reports will use the view and work with real datetime values. This will make queries involving date ranges much easier.
How do I perform this conversion? I created the view but can't find a way to convert the string to a datetime.
Thanks!
Update 1 -
Here's the SQL I have so far. When I try to execute, I get a conversion error "Conversion failed when converting datetime from character string."
How do I handle nulls and datetime strings that are missing the time portion (just yyyymmdd)?
SELECT
dbo.PV1_B.PV1_F44_C1 AS ArrivalDT,
cast(substring(dbo.PV1_B.PV1_F44_C1, 1, 8)+' '+substring(dbo.PV1_B.PV1_F44_C1, 9, 2)+':'+substring(dbo.PV1_B.PV1_F44_C1, 11, 2) as datetime) AS ArrDT,
dbo.MSH_A.MSH_F9_C2 AS MessageType,
dbo.PID_A.PID_F3_C1 AS PRC,
dbo.PID_A.PID_F5_C1 AS LastName,
dbo.PID_A.PID_F5_C2 AS FirstName,
dbo.PID_A.PID_F5_C3 AS MiddleInitial,
dbo.PV1_A.PV1_F2_C1 AS Score,
dbo.MSH_A.MessageID AS MessageId
FROM dbo.MSH_A
INNER JOIN dbo.PID_A ON dbo.MSH_A.MessageID = dbo.PID_A.MessageID
INNER JOIN dbo.PV1_A ON dbo.MSH_A.MessageID = dbo.PV1_A.MessageID
INNER JOIN dbo.PV1_B ON dbo.MSH_A.MessageID = dbo.PV1_B.MessageID
According to here, there's no out-of-the-box CONVERT to get from your yyyymmddhhmm format to datetime.
Your strategy will be parsing the string to one of the formats provided on the documentation, then convert it.
declare #S varchar(12)
set #S = '201107062114'
select cast(substring(#S, 1, 8)+' '+substring(#S, 9, 2)+':'+substring(#S, 11, 2) as datetime)
Result:
2011-07-06 21:14:00.000'
This first changes your date string to 20110706 21:14. Date format yyyymmdd as a string is safe to convert to datetime in SQL Server regardless of SET DATEFORMAT setting.
Edit:
declare #T table(S varchar(12))
insert into #T values('201107062114')
insert into #T values('20110706')
insert into #T values(null)
select
case len(S)
when 12 then cast(substring(S, 1, 8)+' '+substring(S, 9, 2)+':'+substring(S, 11, 2) as datetime)
when 8 then cast(S as datetime)
end
from #T
Result:
2011-07-06 21:14:00.000
2011-07-06 00:00:00.000
NULL
You can use CAST or CONVERT.
Example from the site:
G. Using CAST and CONVERT with
datetime data
The following example displays the
current date and time, uses CAST to
change the current date and time to a
character data type, and then uses
CONVERT display the date and time in
the ISO 8901 format.
SELECT
GETDATE() AS UnconvertedDateTime,
CAST(GETDATE() AS nvarchar(30)) AS UsingCast,
CONVERT(nvarchar(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO
Here is the result set.
UnconvertedDateTime UsingCast UsingConvertTo_ISO8601
----------------------- ------------------------------ ------------------------------
2006-04-18 09:58:04.570 Apr 18 2006 9:58AM 2006-04-18T09:58:04.570
(1 row(s) affected)
Generally, you can use this code:
SELECT convert(datetime,'20110706',112)
If you need to force SQL Server to use a custom format string, use the following code:
SET DATEFORMAT ymd
SELECT convert(datetime,'20110706')
A one liner:
declare #datestring varchar(255)
set #datestring = '201102281723'
select convert(datetime, stuff(stuff(#datestring,9,0,' '),12,0,':') , 112 )
Result:
2011-02-28 17:23:00.000
DECLARE #d VARCHAR(12);
SET #d = '201101011235';
SELECT CONVERT(SMALLDATETIME, STUFF(STUFF(#d,9,0,' '),12,0,':'));
Note that by storing date/time data using an inappropriate data type, you cannot prevent bad data from ending up in here. So it might be safer to do this:
WITH x(d) AS
(
SELECT d = '201101011235'
UNION SELECT '201101011267' -- not valid
UNION SELECT NULL -- NULL
UNION SELECT '20110101' -- yyyymmdd only
),
y(d, dt) AS
(
SELECT d,
dt = STUFF(STUFF(LEFT(d+'000000',12),9,0,' '),12,0,':')
FROM x
)
SELECT CONVERT(SMALLDATETIME, dt), ''
FROM y
WHERE ISDATE(dt) = 1 OR d IS NULL
UNION
SELECT NULL, d
FROM y
WHERE ISDATE(dt) = 0 AND d IS NOT NULL;
DECLARE #test varchar(100) = '201104050800'
DECLARE #dt smalldatetime
SELECT #dt = SUBSTRING(#test, 5, 2)
+ '/' + SUBSTRING(#test, 7, 2) + '/'
+ SUBSTRING(#test, 1, 4) + ' ' + SUBSTRING(#test, 9, 2)
+ ':' + SUBSTRING(#test, 11, 2)
SELECT #dt
Output:
2011-04-05 08:00:00