SQL Server - How to convert varchar to date - sql

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;

Related

Convert varchar to date without timestamp

I am trying to convert/select the nvarchar datatype to date format (YYYY-MM-DD).
The table contains the date in DD/MM/YYYY format & also the null values.
Below SQL query is working fine but it has timestamp in the output
select Date4 = Convert(datetime, Last_Paid_Date, 103) FROM table
2021-01-30 00:00:00.000
My requirement is to have only the date in (YYYY-MM-DD) format
normally this should work
select Convert(date, Last_Paid_Date, 103) from tablename
But if you get conversion errors you can try this
SELECT convert(date, convert(datetime, Last_Paid_Date, 103)) FROM TableName
if Date cannot be used to convert from your format, the trick is to convert to a datetime first, and then convert that into a date.
Much much better would be to store the data in a column with type Date instead of varchar off course
I find this also some good reading
EDIT
if you keep getting conversion errors, then probably there are invalid dates in your varchar column. That is why you should never never never store dates/time in a varchar column.
To fix this, you could use this
SELECT try_Convert(date, Last_Paid_Date, 103) from tablename
this will put NULL in all columns that have an invalid date/time.
Drawback is that from all the rows that will have a value NULL, you cannot know if the original value was also NULL or an invalid date/time value.
Please try the below.
SELECT Date4 = CONVERT(DATE, Last_Paid_Date, 103) FROM TableName
OR
SELECT Date4 = CAST(GETDATE() AS DATE) FROM TableName
This will remove the Timestamp and give you only the Date values in the (YYYY-MM-DD) format.
You can go for simple conversion.
SELECT Convert(date, '20/01/2020', 103)
2020-01-20
You can go for conversion for the table as given below:
SELECT Convert(date, val, 103) as dateval FROM
(
values
('20/01/2020'),(null)
) as t(val)
dateval
2020-01-20
NULL
The issue with your query is that the column: "Last_Paid_Date" contains NULL String, which needs the conversion as they are characters.
You can try the below query:
SELECT convert(date, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
, convert(datetime, REPLACE(Last_Paid_Date,'NULL','01/01/2001'), 103)
FROM table
The query will replace the NULL strings with a default value if any and then do the date/datetime conversions accordingly
You can chain two conversions : the first one converts the original dd/mm/yyyy (103) to a datetime value, and the second conversion turns that datetime into a yyyy-mm-dd (120) string.
select Date4 = convert(varchar(10), convert(date, Last_Paid_Date, 103), 120)
from table

I have date stored in varchar in SQL Server as '19-09-2020' and I want to convert it to '2020-09-19'

I have date stored in a varchar column in SQL Server as '19-09-2020'.
I want to convert it to '2020-09-19'.
I have tried this but it's not working:
select convert(varchar, '19-09-2020', 23)
You must specify the source format for convert:
convert(date, '19-09-2020',105)
This results in a DATE, if you actually want a VarChar again (of course, you shouldn't):
convert(varchar(10), convert(date, '19-09-2020',105), 23)
Do you want string functions?
select concat_ws('-', right(mycol, 4), substring(mycol, 4, 2), left(mycol, 2))
from mytable
On the other hand, if you want to generate a date from that string, then:
select convert(date, mycol, 105)
from mytable

How to convert string in 'DD/MM/YYYY' or 'YYYY-MM-DD' into date in SQL Server?

I've got a string here which needs to be converted into date but the problem is that it could either be in 'DD/MM/YYYY' or 'YYYY-MM-DD' format.
I've already tried convert which only works for one of the two formats but not both:
declare #string nvarchar(255) = '2019-05-21'
declare #table table (date date)
insert into #table
select convert(date, #string, 111) as date
select * from #table
declare #string nvarchar(255) = '21/05/2019'
declare #table table (date date)
insert into #table
select convert(date, #string, 103) as date
select * from #table
Both of the above solutions result in an error is I use the other format.
Is there a way to get a string converted to date regardless of what format it is in?
Use try_convert():
insert into #table
select coalesce(try_convert(date, #string, 111),
try_convert(date, #string, 103)
) as date
try_convert() returns NULL if the conversion fails. In that case, the conversion will move on to the next pattern. With coalesce(), you can have as many different formats as you like.
You can use TRY_PARSE or PARSE to parse the date literal using a specific culture.
The second format YYYY-MM-DD is an unambiguous date format for the "new" date types like date and datetime2. It's not affected by the DATEFORMAT setting like datetime.
This means you only need to find one culture that can handle the first format. All of the following queries will return the same value :
select parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
select try_parse('21/05/2019' as date using 'en-GB')
-----
2019-05-21
select try_parse('2019-05-21' as date using 'en-GB')
-----
2019-05-21
If you are on SQL 2012 and above, you can use the FORMAT function.
The signature of this function is - FORMAT (value,format[,culture])
Example: SELECT FORMAT (getdate(), 'dd-MM-yyyy') as date and in your case SELECT FORMAT(CAST(<str_value> as DATE), 'yyyy-mm-dd')

Convert ISO-8601 varchar (0000-00-00T00:00:00+00:00) to datetime in SQL

How can I convert 2019-07-01T00:00:00+05:30 to DateTime in SQL?
2019-07-01T00:00:00+05:30 is a varchar field. I need to convert this into DateTime to compare this to a date field.
suggest me a query to Convert (2019-07-01T00:00:00+05:30) into DateTime
Convert To date :
select cast('2019-07-01T00:00:00+05:30' as Date)
Convert To time:
select cast('2019-07-01T00:00:00+05:30' as Time)
Convert To datetime :
select convert(datetime2, '2019-07-01T10:00:30+05:30',0)
Try any of these..
select cast(convert(datetime2, '2019-07-01T10:00:30+05:30',0) as datetime)
select convert(datetime2, '2019-07-01T10:00:30+05:30',0)
One option would be to use a combination of CONVERT on the timestamp without the timezone component, then use TODATETIMEOFFSET with the timezone portion to get the final result:
WITH yourTable AS (
SELECT '2019-07-01T00:00:00+05:30' AS dt
)
SELECT
TODATETIMEOFFSET(CONVERT(datetime, LEFT(dt, 19), 126), RIGHT(dt, 6)) AS output
FROM yourTable;
This outputs:
01/07/2019 00:00:00 +05:30
Demo
Unfortunately, SQL Server truncates the time zone information when converting from datetimeoffset to dateordatetime`. But, you can calculate the offset and add it back in:
select dateadd(minute,
datediff(minute, convert(datetimeoffset, dt), convert(datetime, convert(datetimeoffset, dt))),
convert(datetime, convert(datetimeoffset, dt))
)
from (values ('2019-07-01T00:00:00+05:30')) v(dt);
For your particular timezone, the date at midnight matches the UTC date, so you are safe. I'm on the other side of the world, so this would be a more important consideration in the "western" world ("west" being west of UTC).
The following query will convert the given VARCHAR to DATETIME value:
DECLARE #DateVal AS VARCHAR (30) = '2019-07-01T00:00:00+05:30';
SELECT CAST(REPLACE(SUBSTRING(#DateVal, 0, CHARINDEX('+', #DateVal)), 'T', ' ') AS DATETIME);

Convert Nvarchar DD/MM/YYYY to YYYY-MM-DD in SQL Query

Hi I have a column in my 'Users' table called 'PersonalDetails_DOB'.
The data type is a NVARCHAR(10) and the 'format' the data is currently in DD/MM/YYYY.
I want to change the format to YYYY.MM.DD or YYYY-MM-DD, how would I do this?
I have already tried a running a query in SQL:
SELECT CONVERT(nvarchar(10), PersonalDetails_DOB, 102) as
'PersonalDetails_DOB' FROM Users;
Nothing happens and it doesn't change any date from e.g. 06/02/1967 to 1967.02.06
You need two convert() function :
SELECT PersonalDetails_DOB,
CONVERT(VARCHAR(10), CONVERT(DATE, PersonalDetails_DOB, 103), 102)
FROM Users;
Store dates as dates, not strings. I recommend you pull the value as a date and not a string:
SELECT CONVERT(date, PersonalDetails_DOB, 103) as PersonalDetails_DOB
FROM Users;
You are safer using try_convert():
SELECT TRY_CONVERT(date, PersonalDetails_DOB, 103) as PersonalDetails_DOB
FROM Users;
To find the bad values, you can do:
select PersonalDetails_DOB
from users
where TRY_CONVERT(date, PersonalDetails_DOB, 103) is null;
You can convert back a string if you want.
I would recommend that you fix the data structure. This should work:
update users
set PersonalDetails_DOB = CONVERT(date, PersonalDetails_DOB, 103);
alter users alter column PersonalDetails_DOB date;
You can try the below query to update the date values format and also their data type using SUBSTRING() function as shown below
declare #PersonalDetails_DOB NVARCHAR(10)
set #PersonalDetails_DOB = '13/10/2018' --dd/MM/yyyy
select SUBSTRING(#PersonalDetails_DOB,7,4) + '-' + SUBSTRING(#PersonalDetails_DOB,4,2)
+ '-' + SUBSTRING(#PersonalDetails_DOB,1,2)
-- yyyy-MM-dd
create table Users(PersonalDetails_DOB NVARCHAR(10))
insert into Users values ('01/10/2018')
select * from Users --Before Update
--Updating date values
update Users
set PersonalDetails_DOB = (
SUBSTRING(#PersonalDetails_DOB,7,4) + '-' + SUBSTRING(#PersonalDetails_DOB,4,2)
+ '-' + SUBSTRING(#PersonalDetails_DOB,1,2)
)where PersonalDetails_DOB is not null
select * from Users --After Update
--Change the datatype
ALTER TABLE Users
ALTER COLUMN PersonalDetails_DOB date;
You can find the live demo Live Demo Here
Maybe you should first set dateformat before conversion:
set dateformat dmy;
select PersonalDetails_DOB
,convert(nvarchar(10), cast(PersonalDetails_DOB as datetime), 102) as ANSI_DOB
,convert(nvarchar(10), cast(PersonalDetails_DOB as datetime), 120) as ODBC_DOB
from Users;