How to convert string to datetime in SQL - sql

I have done my share in converting string to date in SQL Server 2016 but never seen a date with the format like the one below. I have looked online for a possible way to convert it without success. Any help helping me converting the string below to datetime datatype in SQL will be appreciated.
Fri Aug 24 2018 22:28:40
Regards,

Found a way to do it in SQL Server:
select cast(right("string",20) as datetime) as dateColumn
from table

When dealing with non-standard date formats, I usually lookup CONVERT function in SQL Server, as it io very "elastic": you can provide various formats to it, so it recognizes them appropriately.
I use this site for reference. There you can find, that the closest date format is indicated by 100:
0 100 mon dd yyyy hh:miAM/PM Default
It's your format except it doesn't include unnecessary in this case day of week information. So all you need to do is cut out the Fri part:
substring(myDatetimestring, 5, 1000)
or even better
substring(myDatetimeString, charindex(' ', myDatetimeString), 1000)
if the day of week part may have variable length. Don't worry about 1000, it only assures that we will have the rest of the string, not any less.
Now we have proper date format, since it says that it's default, we don't need to supply 100 to convert function and also we can use cast function instead, as you discovered, so we could do:
cast(substring(myDatetimeString, charindex(' ', myDatetimeString), 1000) as datetime)
or
convert(datetime, substring(myDatetimeString, charindex(' ', myDatetimeString), 1000), 100)
or
convert(datetime, substring(myDatetimeString, charindex(' ', myDatetimeString), 1000))

Related

T-SQL convert string from ddmmyyyy to dd MMM yyyy

I have string 20120821 and I need to convert it into 21 AUG 2012 string also. What is easy way?
There's a big list of the different outputs that you can find here.
But to answer your questions:
DECLARE #date VARCHAR(8) = '20120821';
SELECT CONVERT(VARCHAR(11), CONVERT(DATE, #date), 113);
declare #t varchar(50) = '20120821'
select convert(varchar(50),convert(date,#t),113)
You can convert to a date using datefromparts():
select datefromparts(right(ddmmyyyy, 4), substring(ddmmyyyy, 3, 2), left(ddmmyyyy, 2))
Then you can convert to a string:
select convert(varchar(255), datefromparts(right(ddmmyyyy, 4), substring(ddmmyyyy, 3, 2), left(ddmmyyyy, 2)), 106)
Use cast and convert like:
select convert(varchar, cast('20120821' as datetime), 6)
or
select convert(varchar, cast('20120821' as datetime), 113)
Tough this question already have four answers - none of the existing answers is much more than a code dump - so I figured I would add a little explanation.
String representations of dates are considered notorious because a lot of them are ambiguous - For example, 02/04/2019 can be interpreted as either February 4th 2019 or as April 2nd 2019.
It gets worst when you have a two digit year - 01/02/03 can represent so many different dates - including different centuries!
Lucky for you, your source string is in one of the two formats that are guaranteed to always be interpreted correctly by SQL Server when converting to Date (but not to DateTime!):
yyyymmdd is one and yyyy-mm-dd is the other.
Both of these formats are international standard and described in ISO 8601.
Please note, however, that there is a known bug (feature?) in the DateTime data type that makes the yyyy-mm-dd format culture dependent. This bug does not exists in the new and improved alternative data type called DateTime2.
I will not add a code to this answer since it would just be repeating the code from Jim Jimson's answer or from apomene's answer.

How to write a query to select data with a date format 'DD-MMM-YYYY'?

I want to write a query in SELECT statement with the format 'DD-MMM-YYYY' eg:
'1-Jan-2019' or '23-Mar-2018'
Simply
SELECT CONVERT(VARCHAR, GetDate(), 106)
Returns:
23 Jan 2019
See CAST and CONVERT where the Date and Time Styles
If you really want to return '-' separator, you can do as
SELECT REPLACE(CONVERT(VARCHAR, GetDate(), 106), ' ', '-')
Returns:
23-Jan-2019
You can leverage T-SQL FORMAT() to request exact format of the output and culture as you require:
SELECT FORMAT(GETDATE(), '%d-MMM-yyyy', 'en')
It is available since SQL Server 2012
However, better practice is to control format on an app level
If you drop the dashes e.g. '1 jan 2018' then that works out of the box. It is also a really nifty format that always works if you don't know the database settings.
Just remember that month names are abbriviated differently for different languages.
You can do that pretty easily with a Convert call in SQL to a numbered format. It will be close to what you want, but for your format exactly you will need to replace the spaces in the string with dashses by using a Replace call on the result of the convert.
Reference: https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017
Example:
select REPLACE(CONVERT(VARCHAR(20), GetDate(), 106), ' ', '-')

How to convert “Thu Jun 11 00:49:35 IST 2015” to “YYYY-MM-DD hh:mm:ss” in SQL Server?

How to convert “Thu Jun 11 00:49:35 IST 2015” to “YYYY-MM-DD hh:mm:ss” in SQL Server?
I tried to convert and casting but it's throwing an error
A few things to note about this before I posit a solution:
The source of this information should be modified, if at all possible, to conform to some ISO-standard date.
SQL Server pre-2016 doesn't handle time zone names well, so I'm going to presume that all of your strings contain "IST". If they don't, you'll have to adjust accordingly by searching for them and creating some kind of switch case to modify the resulting datetimeoffset.
I have no idea whether your day representation is two-digit or variable-digit. I've assumed that it's variable, but you can probably simplify this answer with fixed-string parsing if it's two-digit.
Since you have a timezone, the target representation of YYYY-MM-DD hh:mm:ss is ambiguous. I've converted it here to UTC.
If your string is in a table called Dates with column HorribleString, then:
select
convert(varchar(100), convert(datetime2, convert(datetimeoffset,
substring(HorribleString, len(HorribleString) - 3, 4) -- Year
+ substring(HorribleString, 4, len(HorribleString) - 12) -- len(Thu ) + len( IST 2015) = 12
+ case substring(HorribleString, len(HorribleString) - 7, 3) -- Timezone
when 'IST' then ' +05:30'
else ''
end
, 109), 1), 20)
from
Dates

Converting date format sql

I am taking information from one database with the datetime string formatted like this
2011-08-25 13:53:22.607
and would like to format it to look like
8/25/2011 01:53:22 PM
Please suggest a way for me to do this.
in Sql Server try:
DECLARE #YourDatetime datetime
SELECT #YourDateTime='2011-08-25 13:53:22.607'
SELECT
CONVERT(varchar(2),month(#YourDateTime))+'/'+CONVERT(varchar(2),day(#YourDateTime))+'/'+CONVERT(varchar(4),year(#YourDateTime)) --date remove leading zeros
+' '+RIGHT('0'+LTRIM(LEFT(RIGHT(convert(varchar(50),#YourDateTime,109),14),8)),8) --amp/pm time format keep leading zeros
+' '+RIGHT(convert(varchar(50),#YourDateTime,109),2) --am or pm
output:
----------------------
8/25/2011 01:53:22 PM
(1 row(s) affected)
There is a good article on date formatting in SQL Server here: http://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/
It was written with SQL Server 2005 in mind but the information is still relevant.
There is no native m/d/yyyy style. You can get close (leading 0s on month and day, no leading 0 on hour) with this:
DECLARE #d DATETIME = '2011-08-25 13:53:22.607';
SELECT CONVERT(CHAR(10), #d, 101) + ' '
+ LTRIM(RIGHT(CONVERT(VARCHAR(25), #d, 22), 12));
You can do a lot more work to manipulate the strings to get exactly the format you're after, but for now I'd suggest doing that formatting in the application/presentation tier instead of arm-wrestling SQL Server into doing it.
In Denali you will be able to use FORMAT() with much more control and less ugly string manipulation (a.k.a. manual labor), e.g.
SELECT FORMAT(#d, 'M/d/yyyy hh:mm:ss tt');

SQL Server: How to get current date time in YYYYMMDDHHMISSMSS

I need the current date time in the format YYYYMMDDHHMISSMIS
Example:
20110723233747607
By using the CURRENT_TIMESTAMP or getdate() functions, we can retrieve the current datetime into 2011-07-23 23:37:47.607 format. If I use REPLACE and CONVERT functions to remove the "-" and ":" characters, then I get the value into
Jul 23 2011 11:37PM
...format. But I need the current date time as 20110723233747607 to use it for my another purpose.
My SQL query is:
SELECT REPLACE(CONVERT(VARCHAR(20), CURRENT_TIMESTAMP),'.','')
output: Jul 23 2011 11:37PM
So how can I get the current date time in my required format? Pls help.
select replace(
replace(
replace(
replace(convert(varchar(23), getdate(), 121),
'-',''),
'.',''),
' ',''),
':','')
I do not know why you need to use so many REPLACE() functions. Usage of functions really reduce the execution time. I used two CONVERT and one REPLACE function below.
SELECT CONVERT(VARCHAR(8), GETDATE(), 112) + REPLACE(CONVERT(VARCHAR(12), GETDATE(), 114),':','')