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

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)

Related

SQL server - converting string to datetime

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

SQL Server - How to convert varchar to date

I have a table containing StartDate in the format dd/mm/yyyy and yyyy-mm-dd.
I want to convert this varchar column to DATE type in the format DD/MM/YYYY.
I have tried the below.
select CONVERT(varchar(20),StartDate,103) AS [FormattedDate]
and
CONVERT(VARCHAR(20),(CAST([StartDate] AS DATE)),103)
I get the error -Conversion failed when converting date and/or time from character string.
Pls suggest.
if you only have the date string in dd/mm/yyyy or yyyy-mm-dd
select case when substring(StartDate, 3, 1) = '/'
then convert(date, StartDate, 103)
else convert(date, StartDate, 121)
end
SQL Server is actually quite good about figuring out formats for a date conversion with no formatting argument. However, it is going to assume MM/DD/YYYY for the second format and generate an error.
So, you can use try_convert() and coalesce():
select coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
)
Here is a SQL Fiddle.
Then, you should go into your data and fix the column. Here is one method:
update t
set startdate = coalesce(try_convert(date, startdate, 103),
convert(date, startdate)
);
alter table t alter column startdate date;
You can add additional formatting for the result set by turning the date back into a string, using convert().
To get YYYY-MM-DD use SELECT CONVERT(varchar, getdate(), 23)
To get MM/DD/YYYY use SELECT CONVERT(varchar, getdate(), 1)
For detailed explaination try this.
Here's an example that first tries to convert the VARCHAR from a 'yyyy-mm-dd' format to the 'dd/mm/yyyy' format.
If that doesn't work out, then it just assumes it's already in the 'dd/mm/yyyy' format.
And then defaults to the first 10 characters from the string.
declare #TestTable table (StartDate varchar(10), DateFormatUsed varchar(10));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate() ,103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
;
select t.*,
coalesce(convert(varchar(10), try_convert(date,StartDate,20),103), left(StartDate,10)) as [FormattedDate]
from #TestTable t;
But try_convert is only available since MS SQL Server 2012.
For MS SQL Server 2008 we can use a CASE WHEN with a LIKE to check the format.
declare #TestTable table (StartDate varchar(30), DateFormatUsed varchar(30));
insert into #TestTable (StartDate, DateFormatUsed) values
(convert(varchar(10),GetDate(), 103), 'dd/mm/yyyy')
,(convert(varchar(10),GetDate(), 20), 'yyyy-mm-dd')
,(convert(varchar(19),GetDate(), 20), 'yyyy-mm-dd hh:mi:ss')
;
select t.*,
(case
when StartDate like '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]%'
then convert(varchar(10), convert(date, left(StartDate, 10), 20), 103)
else left(StartDate, 10)
end) as [FormattedDate]
from #TestTable t;

How do I convert text to datetime in SQL Server?

I want to convert text to datetime in SQL Server.
I have text which in the format dd/mm/yyyy, but I want to convert this text format to datetime yyyymmdd.
I am using this method.
Convert(varchar(8), Right(text, 4) + Substring(text, 4, 2) + Left(text, 2), 112)
BUT I need a simpler query.
Answer:
SELECT FORMAT(CONVERT(date, '30/01/2018', 103), 'yyyyMMdd')
Explanation:
So this one is a little trickier because you've got DD/MM/YYYY, so you need to CONVERT first:
SELECT CONVERT(date, '30/01/2018', 103)
Result: 2018-01-30
Then if you are using SQL Server 2012+ use FORMAT()
SELECT FORMAT(CONVERT(date, '30/01/2018', 103), 'yyyyMMdd')
Result: 20180130

Converting dd-mm-yyyy string to date

I am passing a date in string format 11-09-2013 in dd-mm-yyyy format from JSP. My query is:
select convert(varchar(10),'11-09-2013',106)
But it is not giving my expected output, which is:
11-SEP-2013
DECLARE #d CHAR(10) = '11-09-2013'; -- dd-mm-yyyy
SELECT UPPER(REPLACE(CONVERT(CHAR(11), CONVERT(DATETIME, #d, 103), 106), ' ', '-'));
-- if 2008+ you can use DATE instead:
SELECT UPPER(REPLACE(CONVERT(CHAR(11), CONVERT(DATE, #d, 103), 106), ' ', '-'));
-- if 2012 you can use:
SELECT UPPER(FORMAT(CONVERT(DATE, #d, 103), 'dd-MMM-yyyy'));
Result in all three cases:
11-SEP-2013
However, this can be very expensive to convert to strings etc. like this. Why do you need this output format, and where is it going? If this is being presented at the client you are much better off using the string formatting capabilities at the client.

Convert SQL DateTime format

How can I display a DATETIME value (2010-12-02 15:20:17.000) as 02/12-2010 15:20?
For SQL Server:
select stuff(convert(varchar, getdate(), 105), 3, 1, '/') + ' ' + left(convert(varchar, getdate(), 8), 5)
DateTime is a DateTime is a DateTime - it just holds a date and time and doesn't have any string representation, really.
See the CAST and CONVERT topic in the SQL Server Books Online for details - it shows all supported date formats that SQL Server supports.
For your source format (2010-12-02 15:20:17.000) you could probably use style no. 121
DECLARE #source VARCHAR(50)
SET #source = '2010-12-02 15:20:17.000'
DECLARE #Date DATETIME
SELECT #Date = CONVERT(DATETIME, #source, 121)
SELECT #Date
but your target format is a bit odd..... I don't see any "out of the box" style that would match your needs. You'll need to use some string manipulation code to get that exact format.
Use MSSQL's build-in function to convert datetime to string with format,
SELECT CONVERT(VARCHAR(8), GETDATE(), 1) AS [MM/DD/YY] --2/5/12
SELECT CONVERT(VARCHAR(10), GETDATE(), 103) AS [DD/MM/YYYY] --5/2/2012
You need to create custom function to get various format to use like this;
SELECT dbo.ufn_FormatDateTime(GETDATE(),'YYYY-MM-DD HH:mm:SS tt')
--Output : 2012-02-05 01:58:38 AM
SELECT dbo.ufn_FormatDateTime(GETDATE(),'(dddd) mmmm dd, yyyy hh:mm:ss.fff tt')
--Output : (Sunday) February 05, 2012 01:58:38.723 AM
SELECT dbo.ufn_FormatDateTime(GETDATE(),'dd/MM/yyyy')
--Output : 05/02/2012
SELECT dbo.ufn_FormatDateTime(GETDATE(),'yyyy MMM, dd (ddd) hh:mm:ss tt')
-- Output : 2012 Feb, 05 (Sun) 01:58:38 AM
Get the code snippet from this link.
http://www.tainyan.com/codesnippets/entry-62/sql-server-date-time-format-function.html
http://msdn.microsoft.com/en-us/library/ms189491.aspx
Is this what you're looking for?
Assuming Oracle:
select TO_CHAR(SYSDATE, "dd/mm-yyyy HH24:mi")
from DUAL;
Assuming SQL Server:
select STR(DATEPART(DAY, GETDATE()), 2)
+ '/'
+ STR(DATEPART(MONTH, GETDATE()), 2)
+ '-'
+ STR(DATEPART(YEAR, GETDATE()), 4)
+ ' '
+ STR(DATEPART(HOUR, GETDATE()), 2)
+ ':'
+ STR(DATEPART(MINUTE, GETDATE()), 2);
Little example I use for Germany and Switzerland: dd.mm.yyyy hh:mm
SELECT CONVERT(varchar, GETDATE(), 104) + ' ' + LEFT(CONVERT(varchar, GETDATE(), 108), 5)