Click here to Skip to main content
15,886,778 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I know basics of converting datetime to required format but I am in a situation
to convert datetime to varchar in a different format.

If I Enter date as 2015-02-27 19:31:30.623

I should get my desired output in the following format.

02/27/2015 7:31 PM

I hope I would get an answer as soon as possible.
Posted
Comments
PIEBALDconsult 27-Feb-15 9:23am    
Please leave the formatting to the UI and don't do it in the database.
And never store dates as strings.
KUMAR619 27-Feb-15 9:36am    
Client wants to see the Post in requested format as a string.
PIEBALDconsult 27-Feb-15 9:39am    
Yes, in some UI I expect, maybe a web page?

yes, the formatting should be left up to the presentation layer in your app, but if you want to display it differently in a sql query you could use CONVERT:
http://www.sql-server-helper.com/tips/date-formats.aspx[^]

if you have sql 2012 and above, you could use FORMAT
https://msdn.microsoft.com/en-us/library/hh213505%28v=sql.110%29.aspx[^]
 
Share this answer
 
See here: http://www.w3schools.com/sql/func_convert.asp[^] for the standard SQL date convert codes: if it isn;t one of those (and it isn't) then you will have to play with the SUBSTRING or DATEPART functions to get exactly what you want.

But as has been mentioned, you shouldn't do this in SQL: it's really a presentation function and should be done as late as possible to ensure that it can be done in the format the user understands.
02/27/2015 is fine - it can be seen as the date easily.
02/03/2015 isn't - in Europe that's the 2nd of March, in the US it's the 3rd of February.

You should not assume an output format unless it's for a very specific report where it has to be that way.
 
Share this answer
 
Hi Kumar,

I think this solution might help you for your desired
output
-----------------------------------
Select Convert(Varchar(10),Cast('2015-02-27' as datetime),101) + ' ' + Convert(Varchar(15),Cast('2015-02-27 19:31:30.623' as TIME),100)
 
Share this answer
 
From all the answers provided I came to know that there are no more default function to make my expected output directly.

Later I came to a conclusion that I could perform by joining my required date and time part separately.

SQL
Select Convert(Varchar(10),Convert(datetime,GETDATE()),101) + ' ' + RTRIM(LTRIM (Convert(Varchar(7),Right(Convert(datetime,GETDATE()),7),100)))
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900