I am trying to port MySQL function DATE_FORMAT(date,'%y-%m-%d %h:%i:%s %p')
to MsSQL equivalent by using CONVERT()
.
How to format equivalent datetime string in SQL SERVER 2012 to give this output '2014-05-24 01:24:37 AM'
?
Asked
Active
Viewed 6.4k times
24
-
2Reopened as SQL Server 2012 has `format` function not in 2008. – Martin Smith May 23 '14 at 20:18
1 Answers
53
In SQL Server 2012 and up you can use FORMAT()
:
SELECT FORMAT(CURRENT_TIMESTAMP, 'yyyy-MM-dd hh:mm:ss tt')
In prior versions, you might need to concatenate two or more different datetime conversions to get what you need, for example:
SELECT
CONVERT(CHAR(10), CURRENT_TIMESTAMP, 23) + ' ' +
RIGHT('0' + LTRIM(RIGHT(CONVERT(CHAR(20), CURRENT_TIMESTAMP, 22), 11)), 11);
See the Date and Time Styles section of CAST and CONVERT (Transact-SQL) for all of the built-in formatting styles.
I would keep in mind that unless you have a good reason for it, I mean a really good reason, formatting is usually a better job for the technology displaying the data.

Cᴏʀʏ
- 105,112
- 20
- 162
- 194