String conversion to valid date - sql-server

I need to convert a string to a valid date format
I have tried using cast and convert functions to no avail.
Convert( mystring, mm/dd/yy)
I have got a string like: Tuesday, July 09, 2019 12:00 AM to get the output mm/dd/yy . I am not able to get this work.
Tuesday, July 09, 2019 12:00 AM---> mm/dd/yy

Try this:
SELECT TRY_PARSE('Tuesday, July 09, 2019 12:00 AM' AS DATETIME USING 'en-US')
to convert to valid date.
Then:
SELECT CONVERT(VARCHAR(10), TRY_PARSE('Tuesday, July 09, 2019 12:00 AM' AS DATETIME USING 'en-US'), 101)
to convert it to mm/dd/yy.

The most important hint was provided by Larnu as a comment: Do not store date as string, rather use the native date formats and think about the string format in output scenarios only.
So hopefully you are trying to fix this technical issue and therefore you need this conversion in order to store the values in neatly typed columns ;-)
The suggestion by gotqn is the best, as you obviously need to use a specific language/culture and TRY_PARSE is the only approach which allows to specify this parameter. TRY_PARSE will need at least v2012 and - this might be a draw back, it is really slow.
So, if this is a one-way-ticket (just one conversion in order to store your values correctly) and you have a very large count of rows, you might go this route:
DECLARE #yourstring VARCHAR(100)='Tuesday, July 09, 2019 12:00 AM';
SET LANGUAGE ENGLISH;
SELECT CAST(SUBSTRING(#yourstring,CHARINDEX(',',#yourstring)+1,100) AS datetime);
The simple idea is: Cut away the leading Weekday's name. The rest is working implitly.

Related

How to specify a SQL fixed day to work in all countries/languages [duplicate]

I have a date as a varchar in the form
DD/MM/YYYY HH:MM:SS AM
e.g.
16/3/2012 4:39:26 PM
I can't see a valid format option for CONVERT() in the MSDN page
Am I missing something or will I have to reformat the varchar field first?
Edit:
Corrected the format, sorry about that
Once you get your story straight, you'll want one of these:
-- if you really meant dd/mm/yyyy then:
SELECT CONVERT(DATETIME, '16/3/2012 4:39:26 PM', 103);
-- if you really meant mm/dd/yyyy then:
SELECT CONVERT(DATETIME, '3/16/2012 4:39:26 PM', 101);
But agreed with Madhivanan. Don't store dates using the wrong data type, and if you must, use an unambiguous format!
Always use proper DATETIME datatype to store dates
YYYYMMDD and YYYYMMDD HH:MM:SS are unambiguous date formats
For more information, refer this
http://beyondrelational.com/modules/2/blogs/70/posts/10898/understanding-datetime-column-part-ii.aspx
This will work.
DECLARE #dt varchar(100)='2012/3/16 4:39:26 PM'
select convert(datetime,#dt,101)

Datetime format in MSSQL

In my aplication I use a DateEdit control and show the date using this format dd/MM/yyyy so the date is save correctly when I use mssql-server 2014 (spanish) but whe I use mssql-server 2008 (english) the date is stored with this fomat MM/dd/yyyy so what I need to know is if there is a way to store the date with the format dd/MM/yyyy no matter the versiĆ³n of mssql-server I use or the lenguage I use?
EDIT: to explain better this is the problem, this text 03/07/2017 is stored in the sqlserver 2014 as july 3 of 2017 and in the sqlserver 2008 is stored as march 7 of 2017.
Convert.ToDateTime(String).ToString("dd-MM-yyyy")
Check the defualt language on your MS SQL Server 2008, and if its possible, you can change to Spanish: How to change Date Format after installing SQL Server
Also, you can format your query output with the CONVERT function (#ZLK post the link) using the format 103: CONVERT (DATETIME,[YOURDATE],103)
Following solution has two options. You can use one as per your requirements.
DECLARE #Date AS TABLE(val VARCHAR(30));
INSERT INTO #Date VALUES('12/04/2016');
INSERT INTO #Date VALUES('10/01/2015');
INSERT INTO #Date VALUES('17/03/2017');
--Option 1
SELECT TRY_PARSE(val AS DATE USING 'en-gb') 'Option 1' FROM #Date;
--Option 2
SELECT CONVERT(VARCHAR(10),TRY_PARSE(val AS DATE USING 'en-gb'),103) 'Option 2' FROM #Date;
And the outputs are:
As others said: SQL doe not store dates as we humans do. But thats another matter.
I think what you need is to inform SQL the format your date has.
The best option is to use ISO 8601 format: yyyy-mm-ddThh:mi:ss.mmm.
So, if before saving the date you just format it with this format, SQL (no matter the version or the language) will recognize it as begining with a year, followed by a month and so on. The key of this subject is using first 4 digits.
This way, 2017-01-03 will always be January 03, 2017 and never March 01, 2017. Hope this help you.
Using this you can change the date Format
select FORMAT(GETDATE(), 'dd/MMM/yyyy', 'en-us')

How to convert date time format in SQL Server 2014

I'm using this query
SELECT convert(nvarchar(MAX), GETDATE(), 22) AS Date
Result: 08/05/16 12:23:08 PM
But I want result like this 8/5/2016 12:23:08 PM
dd/mm/yyyy hh:mm:ss a
As of SQL Server 2012 the FORMAT function is available allowing you to specify the format of data types and is locale-aware so it will consider date formatting in relation to the session's language or optional culture parameter.
You can achieve your custom formatting like so: FORMAT(GETDATE(), 'd/M/yyyy hh:mm:ss tt')
Note your requested format dd/mm/yyyy hh:mm:ss a is incorrect as in the case of single digits you want to remove zero padding i.e. 10/8/2016 not 10/08/2016. That's why in the format string I use only d and M.
Also, pay attention to #GarethD comment about the cost on larger datasets.
You could use the FORMAT function in T-SQL : https://msdn.microsoft.com/en-us/library/hh213505(v=sql.120).aspx
Here is the code :
SELECT FORMAT(GETDATE(), 'd/M/yyyy hh:mm:ss tt')

SQL Server : varchar to Date Conversion/Casting Error

If I use this
SELECT CONVERT(DATE, '26/03/2014', 101)
I get an error:
Conversion failed when converting date and/or time from character string.
But if I use this
SELECT CONVERT(DATE, '26/03/2014', 103)
There's no error and this is the result returned:
2014-03-26
I don't understand why the first code is not working, as far as I searched and understand is that 101 is for US date and 103 is for UK/French Date.
This:
SELECT CONVERT(DATE, '26/03/2014', 101)
will be interpreted in the US way (mm/dd/yyyy) : the 26th month, 3rd day of 2014 - this obviously fails (no 26th month).
This however:
SELECT CONVERT(DATE, '26/03/2014', 103)
will be interpreted the European way (dd/mm/yyyy): the 26th day of the 3rd month (March) of 2014.
You need to very careful with parsing strings to date! Check out all the defined styles for CONVERT here
If you want to be sure it works always, use the ISO-8601 format: YYYYMMDD or in your case:
SELECT CAST('20140326' AS DATE)
will always work, no matter what language/regional settings you have
Thats becuase of the format specifier(101) which you are using.
101 is mm/dd/yyyy
So 26 cannot be a month. Hence resulting in error.
103 is dd/mm/yy
And hence it is working correctly. if the day would have been less than 13, it would have taken it as month and there would be logical error.
The convert signature is as follows
CONVERT(data_type(length),expression,style)
for the date conversion, the styles are as follows
101 mm/dd/yy USA
103 dd/mm/yy British/French
more formats here http://www.w3schools.com/sql/func_convert.asp
Use language neutral date representations for literals. In case with style 101, SQL Server assumed the MM/dd/yyyy instead of dd/MM/yyyy.
Here's a nice link with more info from MVP Tibor Karaszi:
http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

Formatting datetime values

I am retrieving date and time using this:
SELECT convert(varchar, getdate())
and it shows me output as:
Jul 3 2012 9:34PM
but client want that there should be space between time and AM/PM, means output should be like this:
Jul 3 2012 9:34 PM
Thanks in advance.
For one, don't use varchar without length. And you can use STUFF here, e.g.
SELECT STUFF(CONVERT(VARCHAR(19), GETDATE()), 18, 0, ' ');
Results:
Jul 3 2012 12:48 PM
Note that this can look different depending on language and regional settings.
In SQL Server 2012 this is a little more intuitive, however the extra space between month and day when the day is < 10 is tricky to work around (or my understanding of .NET's format is lacking):
SELECT FORMAT(GETDATE(), 'MMM d yyyy hh:mm tt');

Resources