如何在SQL SERVER中格式化日期时间 [英] How to format datetime in SQL SERVER
问题描述
我正在尝试将MySQL函数 DATE_FORMAT(date,'%y-%m-%d%h:%i:%s%p')
移植到MsSQL通过使用 CONVERT()
等效。
如何在SQL SERVER 2012中格式化等效的datetime字符串以给出此输出'2014- 05-24 01:24:37 AM'
?
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'
?
推荐答案
在SQL Server 2012及更高版本中可以使用 FORMAT()
:
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);
请参见所有内置格式设置样式的CAST和CONVERT(Transact-SQL)。
我要记住,除非您有充分的理由,否则我的意思是确实的充分理由,格式化通常是显示技术的更好选择数据。
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.
这篇关于如何在SQL SERVER中格式化日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!