Converting date format sql - 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');

Related

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 string to datetime in 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))

Conversion function to convert the following "11/30/2014" format to Nov-2014

How to covert the following 11/30/2014 into Nov-2014.
11/30/2014 is stored as varchar
Try it like this:
DECLARE #str VARCHAR(100)='11/30/2014';
SELECT FORMAT(CONVERT(DATE,#str,101),'MMM yyyy')
The FORMAT function was introduced with SQL-Server 2012 - very handsome...
Despite the tags you set you stated in a comment, that you are working with SQL Server 2012, so this should be OK for you...
A solution that should work even with Sql server 2005 is using convert, right and replace:
DECLARE #DateString char(10)= '11/30/2014'
SELECT REPLACE(RIGHT(CONVERT(char(11), CONVERT(datetime, #DateString, 101), 106), 8), ' ', '-')
result: Nov-2014
You could use TRY_CONVERT (To avoid breaking if you have any invalid dates) with the style 101 to convert to date, then FORMAT to get your desired output.
SELECT FORMAT(TRY_CONVERT(DATE, '11/30/2014', 101), 'MMM-yyyy')
HOWEVER dates should be stored as dates, and formatting should be left to the presentation layer, so what I would do is sort out your database so that the data is stored as the appropriate type, then you can format the data in your application. This will be a bit of work upfront but will solve a lot of headaches down the road.
It is also worth noting that FORMAT doesn't scale particularly well
select CONVERT(varchar,cast('11/30/2014' as date), 103)
Reference: https://msdn.microsoft.com/en-us/library/ms187928.aspx

How to display monthname and year in SQL Server

If date is 10/16/2015, column is datetime type '2015-10-16 10:09:19.443'
How to display only the month and year as ' Oct-15' in SQL Server?
If you are using SQL Server 2012 or later, you can use the Format() function:
Declare #Date DateTime = '10/16/2015'
Select Format(#Date, N'MMM-yy')
Result:
Oct-15
Edit - in light of #lad2025's comment, if necessary, you may need to also add the en-US locale:
Declare #Date DateTime = '10/16/2015'
Select Format(#Date, N'MMM-yy', 'en-US')
If you are trying to run a quick ad-hock query to see results formatted as MMM-YY, but do not have access to FORMAT function (i.e. use MS SQL Server 2008 or earlier) you can do this:
SELECT replace(right(convert(varchar(9), date_column, 6), 6), ' ', '-')
FROM my_table
However, if you are writing an application, and would like to present the date to end-user in this specific format, you should do the formatting in the host language.
Here's a pretty simple (and quick) way to convert from DATETIME, although I agree with other comments and answers that a parameter should really be kept in the canonical datetime format, that way any date handling is portable across languages:
SELECT RIGHT(REPLACE(CONVERT(VARCHAR(9), CAST('2015-10-16 10:09:19.443' AS DATETIME), 6), ' ', '-'),6) AS [Mon-YY]
Look at DatePart method in SQLServer and extract in postgreSQL.

T-SQL convert varchar yyyy-MM-dd-hh.mm.ss.nnnnnn into datetime

This is in MS SQL Server.
I have a varchar in the format yyyy-MM-dd-hh.mm.ss.nnnnnn
For example: 2010-09-17-20.52.31.870000
I want to convert this into a datetime... but ISDATE function in MSSQL says that is not a valid date and CONVERT won't work. Is there a way to use the convert function so that I can tell it what format the date is in?
I also want to check first that it is a valid date since the varchar input may contain nothing or it may contain an invalid date.
For example, invalid data of 2010-xx-r7-99.53esdfd.31.870000... I would skip that data and not even try to convert.
As far as I'm aware, SQL Server 2005 only supports milliseconds up to 3 digits, so you could replace the periods with colons, and grab the left and right portions (ignoring the hyphen between the day and hours) and come up with something like this:
DECLARE #myDate varchar(50)
SET #myDate = '2010-09-17-20.52.31.870000'
PRINT isdate(left(#myDate, 10) + ' ' +
replace(substring(#myDate, 12, 12), '.', ':')) -- Should print '1'
PRINT cast(left(#myDate, 10) + ' ' +
replace(substring(#myDate, 12, 12), '.', ':') as datetime)
... which will effectively give you 870 milliseconds
The ISO 8601 standard separates the date and time with the letter T. Maybe that's all it needs to convert successfully? Some conversion implementations accept a space there too. I've never seen a hyphen there.
You would have to change the punctuation a bit to make it work, and reduce the precision from microseconds to millisecond. This works:
convert(datetime, '2010-09-17 20:52:31.870', 121)
What you are getting in is a bit wonky, but this works (tested):
DECLARE #temp as varchar(50)
SET #temp = '2010-09-17-20.52.31.870'
SET #temp = replace(#temp,'.',':')
set #temp = stuff(#temp,11,1,'T')
set #temp = stuff(#temp,20,1,'.')
select #temp
select cast(#temp as datetime)
NB I cut off the extra 0s, you could do this with substring if there really are those extra ones.