How to format datetime in SQL SERVER

走远了吗. 提交于 2019-12-05 01:38:11

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.

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