How to format datetime in SQL SERVER

僤鯓⒐⒋嵵緔 提交于 2019-12-22 03:54:30

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/23837672/how-to-format-datetime-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!