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

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')

Related

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);

Converting a Date to Datetime gives error in sql

I am storing a date in a varchar(50) column with values like thie:
1/01/2018
I want to convert these to a Datetime value eg: 2018-01-22 00:00:00.0000000
My SQL is like;
select
[Site],
CONVERT(VARCHAR(50), CAST([InvDay] AS DATETIME), 101) as Date,
from tableA;
But I am getting;
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I tried like this also but same error;
CONVERT(datetime, [InvDay]) as Date,
How can I make this work?
Look at the values that cannot be converted:
select invday
from tableA
where try_cast(invday as date) is null and invday is not null;
It is also unclear if your format is mm/dd/yyyy or dd/mm/yyyy. You can specify a format using convert():
-- mm/dd/yyyy
select invday
from tableA
where try_convert(date, invday, 101) is null and
invday is not null;
-- dd/mm/yyyy
select invday
from tableA
where try_convert(date, invday, 103) is null and
invday is not null;
I think you want to use set dateformat dmy. Here is an example:
declare #d varchar(15)
set #d='13/1/2018'
set dateformat dmy
select convert(datetime,#d)

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;

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

DATETIME SQL Query

I am using SQL Server 2008 Management Studio. I have a datetime column in my table.
When I select all contents of the table, the date column has data like 10/10/2013 12:00:00 AM.
I need a query to display all contents from the table with date column data as 10/10/2013.
SELECT CONVERT(VARCHAR(10), column, 101) -- u.s standard format mm/dd/yyyy
SELECT CONVERT(VARCHAR(10), column, 103) -- British/French standard format dd/mm/yyyy
Try this one (2008 and higher) -
SELECT CAST('10/10/2013 12:00:00 AM' AS DATE)
For 2005 -
SELECT CAST('10/10/2013 12:00:00 AM' AS VARCHAR(10))
Output -
10/10/2013
This will help you
cast(floor(cast(#dateVariable as float)) as datetime)
Using CONVERT function along with styles for DATETIME you can choose the way dates are displayed. 101 would give you mm/dd/yyyy, 103 = dd/mm/yyyy
SELECT CONVERT(NVARCHAR(20),your_datetime_col, 103) FROM your_table
SQLFiddle DEMO
You can use FORMAT() function:
SELECT FORMAT(<your_column>, 'MM/dd/YYYY') FROM <your_table>;
For your question i was created one table as
create table dateverify(date_v varchar(20));
Inserted single column value
declare #a varchar(20);
set #a='10/10/2013';
begin
insert into dateverify(date_v) values(#a);
end;
using below query,
SELECT CONVERT(VARCHAR(20), date_v , 103) AS [DD/MM/YYYY] from dateverify;
got an answer like you are asked..10/10/2013