Convert to DATE T-SQL - sql

I have a field with date in the format dd.mm.yyyy E.x. 29.05.2016. I want to SELECT it as DATE but I get an error when I try the following:
CAST([PublishedDate] AS DATE) AS PublishedOn
Conversion failed when converting date and/or time from character string.
Reading this I tried the following:
CONVERT(VARCHAR(10), [PublishedDate], 126) AS PublishedDate
But it doesn't change the format.
How do I SELECT to have it in YYYY-MM-DD format.
EDIT: I have 3 different date fields with all three having different formats: dd.mm.yyyy | yyyy-mm-dd | yyyy/mm/dd. I want to select all of them with the same format. Since I use this query to build reports, right now I have dates in different formats. Doing the following:
CONVERT(VARCHAR(10), [PublishedDate], 104) AS PublishedOn
CONVERT(VARCHAR(10), [ValidFromDate], 104) AS ValidFrom
Gives me the following

You should use the right format, in your case it would be:
CONVERT(date, [PublishedDate], 104) AS PublishedDate
Also, once it's in a date, datetime or other date datatype, it doesn't have a format at all.
edit: Once you have your values in a date datatype, of course you can recast to a varchar to get the visual representation of the date you need.
edit2: If you want a date datatype, you should convert to date: CONVERT(DATE, [your column], [your format]).
If you want a nvarchar datatype, you should convert to nvarchar: CONVERT(nvarchar(x), [your column], [your format]).
You have an nvarchar that you want to display in a certain format, so you should first convert to date, then back to varchar (I doubt you need unicode):
CONVERT(VARCHAR(10), CONVERT(date, [PublishedDate], 104), 126)
The 104 you have to change for columns that are currently in a different format.
The best solution by far, is to change the datatypes to date. That is a bit of work, but definitely worthwhile.

If you really want the string do like this:
CONVERT(char(10), CONVERT(date,[date], 104),126) AS PublishedDate
Convert the string to date, using the 104 format (dd.mm.yyyy), as it is your original format, then convert the date into string, using the 126 format (yyy-mm-dd)

If you have a newer version of SQL Server, you may try
SELECT COALESCE(TRY_CAST(adate AS DATE), TRY_convert(DATE, adate, 126), TRY_convert(DATE, adate, 104)), format
FROM (
VALUES ('26.04.2017', 'dkformat') ,
('01.01.2017', 'EU format'),
('12.12.12', 'unknown format')
) a(aDate, format)
But you are going down a dangerous path, when you are trying to guess what format your source is in. Been there, done that, had the t-shirt.
I still hate the 0.1% conversions that are wrong.
This solution will result in NULLs, so you can see where your conversion did not succeed.

Related

Change date time format from YYY-MM-DD HH:MM:SS to YYYY.MM.DD HH:MM:SS in SQL Server

I have a table with a column RequestDate with following format 2019-12-01 00:00:00:000. I want to see results like this: 2019.12.01 00:00:00:000.
I used this command
SELECT CONVERT(char(10), RequestDate, 104) AS finaldate
From the above query I am seeing results as 2019.12.01, but I am missing time (00:00:00:000) - how can I keep along with time. I want final results like 2019.12.01 00:00:00:000
I don't think that there is a built-in format specifier for this. But you could do:
replace(convert(varchar, requestDate, 121), '-', '.')
121 gives you format YYYY-MM-DD HH:MM:SS.SSS. You can then replace each occurence of '-' with ':'.
Note that this assumes that you have a datetime datatype to start with. If you have a string, then no need to convert(), you can just replace().

Error when converting varchar to date ddmmyyyy

I have a varchar column with the following format ddmmyyyy and I'm trying to convert it to date in the format dd-mm-yyyy. I'm using the query below but I get the error:
Conversion failed when converting date and/or time from character string.
select *, coalesce(try_convert(date, newdate, 105), convert(date, newdate))
from mydate
You don't have a date, you have a string. So, you can use string operations:
select stuff(stuff(newdate, 5, 0, '-'), 3, 0, '-')
If you want to convert to a date, you can do:
select convert(date, concat(right(newdate, 4), substring(newdate, 3, 2), left(newdate, 2)))
You could then format this as you want.
However, you should not be converting the value to a date. You should be storing it as a date in the first place.
To turn your string to a date, you can just [try_]cast() it; SQL Server is usually flexible enough to figure out the format by itself:
try_cast(newdate as date)
If you want to turn it back to a string in the target format, then you can use format():
format(try_cast(newdate as date), 'dd-MM-yyyy')
Compared to pure string operations, the upside of the try_cast()/format() approach is that it validates that the string is a valid date in the process.
Have to agree with the others. Why are you storing a date as a string in the first place? In a non-standard format, no less? Here's one way, but you should really fix the data model. Store dates as dates.
DECLARE #badIdea table (dt char(8));
INSERT #badIdea(dt) VALUES('21052020');
SELECT newdate = TRY_CONVERT(date, RIGHT(dt,4) + SUBSTRING(dt,3,2) + LEFT(dt,2))
FROM #badIdea;
BTW 105 won't work because it requires dashes. This works:
SELECT CONVERT(date, '21-05-2020', 105);
That's a bad format too, IMHO, because who knows if 07-08-2020 is July 8th or August 7th. But at least that one is supported by SQL Server. Your current choice is not.
SQL doesn't store date data types in different formats, and it's probably not a good idea to try and adjust this.
If, however, you are wanting a result set to simply display the date in a different format, you are on the right track. You just need to convert your date data type to a string.
SELECT *
, COALESCE ( TRY_CONVERT ( CHAR(10), newdate, 105 ), CONVERT ( CHAR(10), newdate ) )
FROM mydate

Dutch varchar date issue in SQL server 13 month

I have the following datetime format ( as varchar ) in my database 13-04-2018 1:05:00.
I need to convert it to the following format: 2018-04-13 01:05:00. As datetime.
Normal convert functions can't do this because they try to take the 13th month, and that month doesn't exist. This error:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
Does someone know how to convert this date issue?
Using datetimes is always a pain regardless of the language because of all the different formats across the world.
To sort your issue out currently, you need to use a format style which is a third parameter to CONVERT. Personally what I would suggest here is to store as a datetime, because storing datetimes as strings is never a good idea. It just gets too messy later on, but if saved in the format you would like, it would be saved as yyyy-MM-dd hh:mm:ss
SELECT CONVERT(DATETIME, '13-04-2018 1:05:00',103)
You can create your own function to format it in your desired output string.
CREATE FUNCTION FormatMyDate
(#Date DATETIME) RETURNS VARCHAR(20)
AS
BEGIN
RETURN FORMAT(#Date,'yyyy-dd-MM hh:mm:ss')
END
And then you can call it in SELECT statements like this:
SELECT dbo.FormatMyDate(yourDateCol)
FROM yourTable
this takes the date from the format where month comes before day and reverses the 2 values (month and day)
SELECT CONVERT(DATETIME, '2018-13-04 01:05:00', 103);
Results:
2018-04-13 01:05:00.000
This should work for you requirement...
SELECT FORMAT(yourdate, 'yyyy-dd-MM')
Your Solution Bro...
DECLARE #d DATETIME = GETDATE()
SELECT FORMAT ( #d, 'MM-dd-yyyy hh:mm:ss', 'de-de' ) AS 'Hoping your result'

Converting string 'yyyy-mm-dd' to date

I want to select from table where date column is equal to specific date which I sending as a string in format 'yyyy-mm-dd'. I need to convert that string and than to compare if I have that date in my table.
For now I am doing this:
select *
FROM table
where CONVERT(char(10), date_column,126) = convert(char(10), '2016-10-28', 126)
date_column is a date type in table and I need to get it from table in this format 'yyyy-mm-dd' and because that I use 126 format. I am just not sure with the other part where I converting string which is already in that format and do I need to convert it because I don't know is it good to use this:
CONVERT(varchar(10), date_column,126) = '2016-10-28'
You don't need to convert the column as well. In fact, you better not convert the column, because using functions on columns prevents sql server from using any indexes that might help the query plan on that column.
Also, you are converting a string to char(10) - better just convert it to date:
where date_column = convert(date, '2016-10-28', 126)
Also, if you are using a datetime data type and not date, you need to check that the datetime value is between the date you pass to the next date.
You can convert string to date as follows using the CONVERT() function by giving a specific format of the input parameter
declare #date date
set #date = CONVERT(date, '2016-10-28', 126)
select #date
You can find the possible format parameter values for SQL Convert date function here
You do not need to do that. yyyy-MM-dd is the default format.
Please note that you need to take into account the time as well, if there's a timestamp in date_column. In that case you should write something like this
... WHERE date_column >= '2016-10-28 00:00:00' AND date_column < '2016-10-29 00:00:00'
... WHERE date_column BETWEEN '2016-10-28 00:00:00' and '2016-10-29 00:00:00'
As I just learned that (other than I thought) BETWEEN actually includes the end timestamp and thus is not equivalent to the above >= ... < approach.
This should use indexes properly as well.

converting varchar to datetime in tsql

I've studied all similar questions here, none of them works, what can be the problem? I want to convert varchar to date
convert(date,substring(replace(ent.Value,' ',''),1,10),103) < '20140101'
It returns error
Conversion failed when converting date and/or time from character string.
ent.Value here is something like '28/02/2014' Actually it works, when I enter something like
convert(date,substring('28/02/2013',1,10),103) < '20140101'
, but it doesn't work directly from the table
Thanks
To convert varchar to datetime : CONVERT(Datetime, '28/02/2014', 103) return the datetime like February, 28 2014 00:00:00+0000
To convert datetime to varchar : CONVERT(VARCHAR(10), datetime_field, 103) return something like '28/02/2014'
In both case you cannot compare it to this kind of text : '20140101'
You can change your text so both informations are ISO like : CONVERT(VARCHAR(10), CONVERT(Datetime, ent.Value, 103), 103) < '01/01/2014'
Or REPLACE(ent.Value,'/','') < '01012014'
But I don't think it's good to compare varchar => you can also do something like this : CONVERT(Datetime, '20140101', 112) :
CONVERT(Datetime, ent.Value, 103) < CONVERT(Datetime, '20140101', 112)
So your both field are in Datetime. ex : SQLFIDDLE DEMO
Break it down a bit: The first conversion works fine with the given example date string, but then you try and compare a DATE to a VARCHAR which requires an implicit conversion. That's never a good sign. However that actually works, so that aside the chances are that you have a date stored in text format that isn't a valid date. Since your examples use the UK date format, perhaps you have an American date in there (02/28/2013 - mm/dd/yyyy). If your default date format is UK style (i.e. you're not using American English settings) then it will fail as being out of range. You might also have entries which aren't dates at all with text in them like wibble or badly formatted dates like 02 Fub 2013.
Basically, you have a duff date somewhere in your table which you'll need to track down. Dates stored as text are a curse and to be avoided at all costs (although I appreciate that's not always possible when you inherit a legacy system - been there myself).
EDIT
To find your possible bad dates try this:
SELECT * FROM MyTable WHERE ISDATE(MyDateAsTextCol) <> 1