Using Substring and Convert Datetime Sql Server 2017 - sql

This is my query:
declare #date char(10)
set #date = '11.08.1982'
select substring(#date,1,2)+ '/'+
SUBSTRING(#date,3,1)+ '/'+ SUBSTRING(#date,4,4) as resultat
I want to use CONVERT function to convert the result to datetime. How can I do this?

You can't convert this to date and time, however you can use replace function :
select replace(#data, '.', '/')

SQL Server is pretty good about picking up the format of a date with no conversion format. So, this works on db<>fiddle, assuming you intend MM.DD.YYYY for the format:
select convert(date, '11.08.1982')
If you want DD.MM.YYYY, then you can explicitly use the "104" format:
select convert(date, '11.08.1982', 104)
You don't have a time component, so I converted these to date. The same works for datetime.

Related

SQL Server : change date format

I need to change the date format from 'yyyy-mm-dd' to 'dd.mm.yyyy'.
I have data in my table like this '2018-08-08', I need convert it to '08.08.2018'.
I have tried:
UPDATE daily_tasks
SET date = REPLACE(date, date, CONVERT(VARCHAR(255), daily_tasks.date, 102))
WHERE 1;
But, it doesn't work.
Ideally you should be storing your dates as bona-fide date columns, not as text. That being said, the date text '2018-08-08' is in fact in an ISO format, and would still allow you to do things like sort and compare against other date literals, so it is not so bad.
But converting this text to a '08.08.2018' format is the wrong thing to do. If a anything, you might want to consider adding a new date column new_date to store this date information. Do that, and then populate it with:
UPDATE daily_tasks
SET new_date = TRY_CONVERT(datetime, date);
Store your date as DATE datatype and when you read data from database use
DECLARE #myDate DATE = '2018-08-08'
SELECT FORMAT(#myDate, 'dd.MM.yyyy')
SELECT CONVERT(VARCHAR(10), #myDate, 104)
Your syntax looks like SQL Sever, so i would do :
UPDATE daily_tasks
SET Col = REPLACE(CONVERT(VARCHAR(10), daily_tasks.date, 103), '/', '.')
WHERE . . . ;
However, i would not recommend to do this, just use CONVERT() with SELECT statement whenever necessary :
SELECT REPLACE(CONVERT(VARCHAR(10), daily_tasks.date, 103), '/', '.')
Regardless of the database, dates are stored in an internal format. This is the correct way to store dates. Do not store dates as strings.
You can specify the format when you query:
CONVERT(VARCHAR(255), daily_tasks.date, 102)
Or, you can even add a computed column to provide this information:
alter table daily_tasks
add date_display as ( CONVERT(VARCHAR(255), daily_tasks.date, 102) ) ;
You could convert the date column to a varchar to store the date in your specified format. However I strongly recommend against this. You should leave it stored as a date.
If you want to do a SELECT to get the data out then you can convert it to your specified format like this:
SELECT CONVERT(VARCHAR, daily_tasks.date, 4)

Convert date to varchar in SQL Server

How do I convert a column which is date type to varchar?
Sample data:
ENDDATE (DATE TYPE)
'1947-12-01 00-00-00'
Requested results:
ENDDATE (VARCHAR)
121947
If I understand the question correctly, you need the ENDDATE of value '1947-12-01 00-00-00' as 121947. You can use the below query
SELECT RIGHT(MONTH(ENDDATE)*1010000+YEAR(ENDDATE),6)
If you are working with 2012 version or higher, you can use format. For earlier versions you can use convert with some string manipulations:
DECLARE #D as date = '1947-12-01'
SELECT REPLACE(RIGHT(CONVERT(char(10), #d, 103), 7), '/', '') As charValue2008,
FORMAT(#d, 'MMyyyy') as charValue2012
Results:
charValue2008 charValue2012
121947 121947
Please note that Format runs relativley slow, so if you have a lot of rows you might want to choose another way to do that.

SQL Server: how to change data entry from VARCHAR to DATETIME?

I have below sample data:
03202012 as date but the column datatype is Varchar.
I want to convert it to 2012-03-20 00:00:00.000 as Datetime.
I tried using
CAST(CONVERT(CHAR(10), Column, 101) AS DATETIME)
But I get an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Complete code snippet to test:
DECLARE #Column VARCHAR(MAX) = '03202012'
SELECT CAST(CONVERT(CHAR(10), #Column, 101) AS DATETIME)
Use yyyyMMdd format, that always works:
DECLARE #myDateString varchar(10) = '03202012';
SELECT cast( substring(#myDateString, 5, 4)+
substring(#myDateString, 1, 2)+
substring(#myDateString, 3, 2) AS datetime);
I found below script help me solved my concern.
SELECT convert(datetime, STUFF(STUFF('31012016',3,0,'-'),6,0,'-'), 105)
Result: 2016-01-31 00:00:00.000
Thanks all for the effort. :D
In MySQL, you can use the STR_TO_DATE function to convert a string to a date. For your example, it would look like this
STR_TO_DATE("03-02-2012", "%m-%d-%Y");
Note that the format part of the string must match the format part of the date.
Edit: Just found out this is for SQL Server, but I assume this will work there as well.

update date format in SQL developer

I need to convert date format in SQL
The current format is yyyy/mm/dd-hh:mm:ss:sss and I need to convert it to yyyy-mm-dd hh:mm:ss CST
I don't really know SQL but did some research and found that I can use instr to find the string and replace it, however, no matter what I try,there is always something off :(
Could anyone here help me with it? thanks in advance.
By the way, it's in oracle sql developer so syntax are different from previous answer. Thanks again
If your current column is stored as a varchar (which it looks like it is based on your example) you can convert it the following way to a datetime.
declare #date varchar(25)
set #date = '2012/02/16-09:40:30:000'
select Convert(datetime, Left(#date, 4) + '-' +
substring(#date, 6, 2) + '-' +
substring(#date, 9, 2) + ' ' +
substring(#date, 12, 8)) As NewDate
And the result would be 2012-02-16 09:40:30.000
There are lots of sites that have details on converting datetime:
http://www.sql-server-helper.com/tips/date-formats.aspx
http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/
If the date is stored as a datetime, then you can get your format by doing:
SELECT convert(varchar, getdate(), 120)
thank you so much for your guys help! I got this sorted out by other user's help, the command is,
update b
set first= to_char(substr(FIRST,1,4)||'-'||substr(FIRST, 6, 2)||'-'||substr(FIRST, 9, 2)||' '||substr(FIRST, 12, 8))
Thanks :)
Mylie
The CONVERT() function is normally used for this. The third parameter lets you specify the required date formatting.
If the date is already in a string, then convert it first into a date type and then convert it back to a string in the required format.
http://msdn.microsoft.com/en-us/library/ms187928.aspx
If you're using SQL Server and it's a date field you can do:
convert(varchar,getdate(),120)
Replacing getdate() with the column name
If the date is stored as a DATETIME, then you can convert it to a string in the format you want by doing the following:
SELECT CONVERT(VARCHAR(19),YourColumn,120)
FROM YourTable
CAST AND CONVERT
declare #ds varchar(23)='2012/02/16 12:57:03:002'; --your current format
select convert(varchar(30),cast(#ds as datetime),120)+' CST' --new format you specified

Convert varchar into datetime in SQL Server

How do I convert a string of format mmddyyyy into datetime in SQL Server 2008?
My target column is in DateTime
I have tried with Convert and most of the Date style values however I get an error message:
'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
OP wants mmddyy and a plain convert will not work for that:
select convert(datetime,'12312009')
Msg 242, Level 16, State 3, Line 1
The conversion of a char data type to a datetime data type resulted in
an out-of-range datetime value
so try this:
DECLARE #Date char(8)
set #Date='12312009'
SELECT CONVERT(datetime,RIGHT(#Date,4)+LEFT(#Date,2)+SUBSTRING(#Date,3,2))
OUTPUT:
-----------------------
2009-12-31 00:00:00.000
(1 row(s) affected)
SQL Server can implicitly cast strings in the form of 'YYYYMMDD' to a datetime - all other strings must be explicitly cast. here are two quick code blocks which will do the conversion from the form you are talking about:
version 1 uses unit variables:
BEGIN
DECLARE #input VARCHAR(8), #mon CHAR(2),
#day char(2), #year char(4), #output DATETIME
SET #input = '10022009' --today's date
SELECT #mon = LEFT(#input, 2), #day = SUBSTRING(#input, 3,2), #year = RIGHT(#input,4)
SELECT #output = #year+#mon+#day
SELECT #output
END
version 2 does not use unit variables:
BEGIN
DECLARE #input CHAR(8), #output DATETIME
SET #input = '10022009' --today's date
SELECT #output = RIGHT(#input,4) + SUBSTRING(#input, 3,2) + LEFT(#input, 2)
SELECT #output
END
Both cases rely on sql server's ability to do that implicit conversion.
Likely you have bad data that cannot convert. Dates should never be stored in varchar becasue it will allow dates such as ASAP or 02/30/2009. Use the isdate() function on your data to find the records which can't convert.
OK I tested with known good data and still got the message. You need to convert to a different format becasue it does not know if 12302009 is mmddyyyy or ddmmyyyy. The format of yyyymmdd is not ambiguous and SQL Server will convert it correctly
I got this to work:
cast( right(#date,4) + left(#date,4) as datetime)
You will still get an error message though if you have any that are in a non-standard format like '112009' or some text value or a true out of range date.
I found this helpful for my conversion, without string manipulation. https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
CONVERT(VARCHAR(23), #lastUploadEndDate, 121)
yyyy-mm-dd hh:mi:ss.mmm(24h) was the format I needed.
Convert would be the normal answer, but the format is not a recognised format for the converter, mm/dd/yyyy could be converted using convert(datetime,yourdatestring,101) but you do not have that format so it fails.
The problem is the format being non-standard, you will have to manipulate it to a standard the convert can understand from those available.
Hacked together, if you can guarentee the format
declare #date char(8)
set #date = '12312009'
select convert(datetime, substring(#date,5,4) + substring(#date,1,2) + substring(#date,3,2),112)
Look at CAST / CONVERT in BOL that should be a start.
If your target column is datetime you don't need to convert it, SQL will do it for you.
Otherwise
CONVERT(datetime, '20090101')
Should do it.
This is a link that should help as well:
I'd use STUFF to insert dividing chars and then use CONVERT with the appropriate style. Something like this:
DECLARE #dt VARCHAR(100)='111290';
SELECT CONVERT(DATETIME,STUFF(STUFF(#dt,3,0,'/'),6,0,'/'),3)
First you use two times STUFF to get 11/12/90 instead of 111290, than you use the 3 to convert this to datetime (or any other fitting format: use . for german, - for british...) More details on CAST and CONVERT
Best was, to store date and time values properly.
This should be either "universal unseparated format" yyyyMMdd
or (especially within XML) it should be ISO8601: yyyy-MM-dd or yyyy-MM-ddThh:mm:ss More details on ISO8601
Any culture specific format will lead into troubles sooner or later...
use Try_Convert:Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
DECLARE #DateString VARCHAR(10) ='20160805'
SELECT TRY_CONVERT(DATETIME,#DateString)
SET #DateString ='Invalid Date'
SELECT TRY_CONVERT(DATETIME,#DateString)
Link:MSDN TRY_CONVERT (Transact-SQL)
I had luck with something similar:
Convert(DATETIME, CONVERT(VARCHAR(2), #Month) + '/' + CONVERT(VARCHAR(2), #Day)
+ '/' + CONVERT(VARCHAR(4), #Year))
The root cause of this issue can be in the regional settings - DB waiting for YYYY-MM-DD while an app sents, for example, DD-MM-YYYY (Russian locale format) as it was in my case. All I did - change locale format from Russian to English (United States) and voilĂ .
This seems the easiest way..
SELECT REPLACE(CONVERT(CHAR(10), GETDATE(), 110),'-','')
SQL standard dates while inserting or updating Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
So if you are inserting/Updating below 1/1/1753 you will get this error.
DECLARE #d char(8)
SET #d = '06082020' /* MMDDYYYY means June 8. 2020 */
SELECT CAST(FORMAT (CAST (#d AS INT), '##/##/####') as DATETIME)
Result returned is the original date string in #d as a DateTime.