SQL server - converting string to datetime - sql

I need to convert a column that contains dates and times in the format 08-JAN-19 09.35.58.173000000 AM to datetime. I've included the code I've tried below - the code commented out is currently not working.
SELECT [last_updated_at]
, SUBSTRING([last_updated_at], 1, 9)
, convert(datetime, SUBSTRING([last_updated_at], 1, 9), 103) as Date
, SUBSTRING([last_updated_at], 11, 18)
--, convert(datetime, SUBSTRING([last_updated_at], 11, 18), 103) as Time --This fails
--, convert(datetime, SUBSTRING([last_updated_at], 1, 9), 103) + convert(datetime, SUBSTRING([last_updated_at], 11, 18), 103) as DateTime --final output datetime column
FROM #temp_dates

The only problem with your data is that you need the time portion of your date to look like this: 2019-01-08 09:35:58.173 instead of 2019-01-08 09.35.58.173 (the dots after the hour and minute need to be colons instead of dots.
--==== Original formatting
DECLARE #date VARCHAR(20) = '08-JAN-19 09.35.58.173000000'
--==== Solution
SELECT CAST(STUFF(STUFF(#date,13,1,':'),16,1,':') AS DATETIME);
Note that this truncates (not rounds) to the nearest millisecond so, 09:35:58.173 becomes 09:35:58.100. If milliseconds are an issue then a bit more finagling will be required.

Please try the below:
select convert(datetime, substring(replace(replace('08-JAN-19 09.35.58.173000000', '-', ' '), '.', ':'), 1, 18))
Before you can convert a string to datetime, your string must conform to certain patterns as shown in https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql?view=sql-server-ver15

Related

How to convert varchar '15:01:2008 02:07:23 PM' to datetime in SQL Server

This is the format of data available
'15:01:2008 02:07:23 PM'
and I want to convert into
'2008-01-15 00:00:00'
SQL Server doesn't have very flexible date parsing capabilities. You can piece this together by parsing the date and times separately. Happily, if you do this as datetime, you can just add the results:
select (convert(datetime, replace(left(str, 10), ':', '/'), 103) +
convert(datetime, right(str, 12))
) as real_datetime
from (values ('15:01:2008 02:07:23 PM')) v(str)

Varchar to Datetime in TSQL

How can I convert date and time value stored like
20200406151341
to DATETIME value 2020/04/06 15:31:41 (YYYY/MM/DD HH:MM:SS.000)? I am unable to find suitable CONVERT() format and the only way so far is to parse the VARCHAR like below.
select dateadd(second, cast(substring('20200406151341',13,2) as int),dateadd(minute, cast(substring('20200406151341',11,2) as int), dateadd(hour,cast(substring('20200406151341',9,2) as int),convert(datetime, left('20200406151341',8), 112)))).
It works yet it's hard to read and understand especially when I have to use it within SELECT statement multiple times.
Also I am surprised query with above conversions is as fast the one with dates stored directly in DATETIME format. Does MSSQL server uses some kind of cache so it does have to do the conversion only once per row?
I use MSSQL Server 2016.
I don't think there is a built in, simple way to do this.
You don't have to go to seconds to do this. You can easily convert the first 8 characters to a date. With some string manipulation, you can convert the last six to a time -- and then add time (as datetime values):
select convert(datetime, left(dt, 8)) + convert(datetime, stuff(stuff(right(dt, 6), 5, 0, ':'), 3, 0, ':'))
from (values ('20200406151341')) v(dt);
You can also use arithmetic rather than 3 dateadd()s:
select dateadd(second,
right(dt, 2) + 60*substring(dt, 11, 2) + 60*60*substring(dt, 9, 2),
convert(datetime, left(dt, 8)))
from (values ('20200406151341')) v(dt)
Note: This uses implicit conversion from a string to an integer (as does your version).
You can use stuff() :
select convert(datetime,
stuff(stuff(stuff(stuff(col, 9, 0, ' '), 10, 0, ''), 12, 0, ':'), 15, 0, ':'
)
Let's throw in a couple more options to the mix:
DECLARE #StrDate varchar(14) = '20200406151341'
SELECT DATETIMEFROMPARTS(
LEFT(#StrDate, 4), -- year
SUBSTRING(#StrDate, 5, 2), -- month
SUBSTRING(#StrDate, 7, 2), -- day
SUBSTRING(#StrDate, 9, 2), -- hour
SUBSTRING(#StrDate, 11, 2), -- minute
SUBSTRING(#StrDate, 13, 2), -- second
0 -- millisecond
) As [Using DateTimeFromParst],
CONVERT(DateTime, LEFT(#StrDate, 8), 112) + -- Date
CONVERT(DateTime, STUFF(STUFF(RIGHT(#StrDate, 6), 5, 0, ':'), 3, 0, ':'), 114) -- Time
As [Using convert and stuff]
Results:
Using DateTimeFromParst Using convert and stuff
2020-04-06 15:13:41 2020-04-06 15:13:41
I suggest using try_convert() or try_cast() in case your strings are invalid, and if invalid they will return NULL instead of raising an error. Refer to the links for further detail on these functions.
declare #val varchar(20)
set #val = '20200416151341'
select try_convert(datetime,
stuff(stuff(stuff(stuff(#val, 9, 0, ' '), 10, 0, ''), 12, 0, ':'), 15, 0, ':')
);
select try_cast(
stuff(stuff(stuff(stuff(#val, 9, 0, ' '), 10, 0, ''), 12, 0, ':'), 15, 0, ':')
as datetime);

Varchar date to datetime sql

I have a varchar date format of 01012018, I need to convert this to a date in a SQL Server view:
CONVERT(VARCHAR(50), CONVERT(DATE, [Date], 103), 103)
I have tried the above with no joy.
Please help
SQL Server can be a bit cumbersome when parsing dates that are not one of the "built-in" ones. You can use parse()/try_parse(), but that is a relatively new function.
In your case, it is pretty simple to construct the date value directly:
select convert(date, concat(right(ddmmyyyy, 4), substring(ddmmyyyy, 3, 2), left(ddmmyyyy, 2)))
from (values ('01012018')) v(ddmmyyyy)
There is no style ddMMyyyy in the CONVERT Date and Time Styles, but there is a dd/MM/yyyy, so you could inject these characters in and convert:
SELECT TRY_CONVERT(date, STUFF(STUFF(v.ddmmyyyy, 5, 0, '/'), 3, 0, '/'), 103)
FROM (VALUES ('01012018')) v (ddmmyyyy);
I've also used TRY_CONVERT incase you have some other "bad" values (perhaps '01312019'). These will return NULL when the varchar represents an invalid date.
Use CONVERT() as
DECLARE #Var VARCHAR(10) = '01012018'
SELECT CONVERT(DATE,
CONCAT( RIGHT(#Var, 4),
SUBSTRING(#Var, 3, 2),
LEFT(#Var, 2)
)
)
Demo
Finally, I would recommend ALTERing your table (which is the right solution) and change the data type of your column to DATE data type.
CREATE TABLE T(
MyCol VARCHAR(10)
);
INSERT INTO T(MyCol) VALUES
('01012018'),
('01022018'),
('01032018'),
('WrongData');
SELECT MyCol
FROM T;
UPDATE T
SET MyCol = TRY_CONVERT(DATE,
CONCAT( RIGHT(MyCol, 4),
SUBSTRING(MyCol, 3, 2),
LEFT(MyCol, 2)
)
);
ALTER TABLE T
ALTER COLUMN MyCol DATE;
SELECT MyCol
FROM T;
Second Demo

How to Convert nvarchar (including time) into datetime

I have data 20160526094432, and I want to convert into datetime in SQLServer
The result will be 2016-05-26 09:44:32
Is there simple way to do that ?
Thanks
If you use MS SQL Server 2012 or newer then you can enjoy format function.
select cast(format(20160526094432,'####-##-## ##:##:##') as datetime) [date-time]
If your long number is a string then you have to convert it.
declare #d varchar(20)='20160526094432'
select cast(format(cast(#d as bigint),'####-##-## ##:##:##') as datetime) [date-time]
Hmmm. I don't think there is a really clean way, but something like this should work:
select (convert(datetime, left(col, 8) as datetime) +
convert(datetime, convert(time,
stuff(stuff(right(col, 6), 5, 0, ':'), 3, 0, ':')
)
)
)
Maybe you can try in this way, for example Date is the column of your table, 103 is the format of Date you want to convert, google for more details.
CONVERT(datetime, Date, 103)

Format SQL DATETIME result like --> 8/25/2011 4:35 PM <-- NOT --> 2011-08-25 16:35:51.000 <--

I have a SQL Query running on SQL Server 2008 R2 that returns a DATETIME column. The current formatting returns this:
2011-08-25 16:35:51.000
and what I would rather see is this:
8/25/2011 4:35 PM
Ideas of how I can modify my SELECT statement? Here a simple statement to work with...
SELECT DtCheckIn from Ticket
Thank you, Andrew
You could do the following:
SELECT convert(varchar, getdate(), 101) + RIGHT(convert(varchar, getdate(), 100), 7)
Resources on date time formatting:
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/
http://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
EDIT - it's a little hokey but it should give you what you are looking for.
Basically the first part SELECT convert(varchar, getdate(), 101) gives you your date 08/25/2011.
The second part SELECT convert(varchar, getdate(), 100) gives you your date and time in the format Aug 25 2011 5:35PM. You only want the time portion which is in the format hh:mmAM or hh:mmPM the total number of characters you want is 7. So if you change this to SELECT RIGHT(convert(varchar, getdate(), 100), 8) you will get your time 5:37PM. I used 8 in my RIGHT() to get an extra space. But now you only want your time not AM/PM so add SELECT LEFT(RIGHT(convert(varchar, getdate(), 100), 8), 6) and you will get your hh:mm.
Finally you want your AM/PM SELECT RIGHT(convert(varchar, getdate(), 100), 2) this will get you the last 2 characters.
Put it all together and you get:
SELECT convert(varchar, getdate(), 101)
+ LEFT(RIGHT(convert(varchar, getdate(), 100), 8), 6)
+ ' ' + RIGHT(convert(varchar, getdate(), 100), 2)
Which gives your final product:
08/25/2011 5:39 PM