How to format datetime in SQL SERVER(如何在 SQL SERVER 中格式化日期时间)
问题描述
我正在尝试使用 将 MySQL 函数
.DATE_FORMAT(date,'%y-%m-%d %h:%i:%s %p')
移植到等效的 MsSQLCONVERT()
如何在 SQL SERVER 2012 中格式化等效的日期时间字符串以提供此输出 '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) 的日期和时间样式部分所有内置格式样式.
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.
这篇关于如何在 SQL SERVER 中格式化日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL SERVER 中格式化日期时间


基础教程推荐
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01