Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format datetime in SQL SERVER

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'?

like image 222
Ankit Avatar asked May 23 '14 20:05

Ankit


1 Answers

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.

like image 67
Cᴏʀʏ Avatar answered Sep 18 '22 22:09

Cᴏʀʏ