Convert varchar to date without timestamp - sql

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

Related

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;

Date convert not working with style 103

I have saved my date as a nvarchar(50) datatype in SQL Server. When I run this query:
select [Client_code], Date_of_receipt
from [T_Receving]
I am getting output like this:
but I want to filter my records by particular date, so I wrote a query like this
select
convert(date, [Date_of_receipt], 103) as 'Date_of_Receipt'
from
[T_Receving]
where
convert(date, [Date_of_receipt], 103) between '2015-03-06' and '2018-05-06'
but its showing an error
Conversion failed when converting date and/or time from character string
You have to convert to datetime and then convert back to varchar
declare #dtv varchar(20) = '2018-17-04'
declare #dtvdt datetime = convert(datetime, #dtv, 103)
select #dtvdt;
select convert(varchar(20), convert(datetime, #dtv, 103), 103), #dtv
where convert(datetime, #dtv, 103) between '2015-03-06' and '2018-05-06'
You clearly have some bad data. Use try_convert():
select try_convert(DATE, Date_of_receipt, 103) as Date_of_Receipt
from T_Receving
where try_convert(DATE, Date_of_receipt, 103) between '2015-03-06' and '2018-05-06' ;
In SQL Server 2008, you have to work harder to find the culprits. You can start with:
select date_of_receipt
from T_Receving
where date_of_receipt not like '[0-3][0-9]/[0-1][0-9]/[0-9][0-9][0-9][0-9]'
This will find most instances of bad formats. If it still persists, you will have to dig deeper to find bad day or month numbers.

Convert Decimal or Varchar into Date

I have 2 fields.
Birth= Datatype Decimal(12,4) & Date = Datatype Date
Birth Date
19650101 2015-07-09
how do i get a result that looks like this
i want the result to be like this
Birth Date
1965-01-01 2015-07-09
where the Birth is a Date datatype and not a decimal (12,4)
To convert the number 19650101 to a date use
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112)
To get the number of years (to one decimal) you could do:
ROUND(
DATEDIFF(day,
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112),
[Date])/365.25
,1)
Which won't be exact but should be close enough to tenths of a year.
You can use this:
-- Create demo data
CREATE TABLE #dates(birth int, date date)
INSERT INTO #dates(birth,date)
VALUES(19650101,N'2015-07-09')
-- Your work
SELECT CONVERT(date,CONVERT(nvarchar(max),birth),112) as birth, date,
DATEDIFF(year,
CONVERT(date,CONVERT(nvarchar(max),birth),112),
date
) as years
FROM #dates
-- Cleanup
DROP TABLE #dates
This depends on the exact format you provides (19650101).
Here is one way to do this conversion.
cast(cast(FLOOR(birth) as CHAR(8)) as DATE)
I think you don't need to round. Just convert your decimal value and put "-" like below : )
select left(birth,4) +'-' +
substring(convert(nvarchar,birth),5,2)+'-'+
substring(convert(nvarchar,birth),7,2)

SQL VarChar to Date

hi
i am trying to convert a VarChar date field (e.g. 20100320) to a real date field like
'dd/mm/yyyy' (e.g. 20/03/2010).
I have tried two ways:
a)
(SELECT MIN(CAST(A.DateOfAction AS Date)) AS Expr1
FROM ResAdm.Action A
WHERE (A.PersonID = P.PersonID))
AS 'Period From',
b)
(SELECT MIN(CONVERT(DATE, A.DateOfAction, 103)) AS Expr1
FROM ResAdm.Action A
WHERE (A.PersonID = P.PersonID))
AS 'Period From',
both producing the result like
yyyy-mm-dd (e.g. 2010-03-20)
but i want the result like
dd/mm/yyyy (e.g. 20/03/2010)
any help will be appreciated.
thanks.
Try this:
select convert(varchar(8), convert(datetime, min(a.DateOfAction), 112), 103)
Your problem is that once you have a date format, SQL Server will dump it out in its default date format, which you've discovered is yyyy-mm-dd. You need to convert from date to varchar to get the format you want. But to convert from date, you need to first convert to date! 112 is the format for yyyymmdd, and 103 is the format for dd/mm/yyyy, so this is why you need these formats. (Books Online reference for date formats)
Declare #date nvarchar(100)
set #date = '20100320'
select convert(varchar, CONVERT(datetime, #date, 109), 103)
You can use
convert(varchar, CONVERT(datetime, A.DateOfAction, 109), 103)