[英]SQL convert datetime to varchar
I want to convert DATETIME to VARCHAR (month/day/year) like this: 我想这样将DATETIME转换为VARCHAR(月/日/年):
10/09/2018 12:00:00.000
I tried using 我尝试使用
Convert(VARCHAR(MAX),[Date & Time Added]),121)
but it returns 但它返回
yyyy-mm-dd hh:mi:ss.mmm
I need the /
format with time, I am Using SQL Server 2012. 我需要带
/
格式的时间,我正在使用SQL Server 2012。
You can use the FORMAT
function: 您可以使用
FORMAT
函数:
SELECT FORMAT(GETDATE(), 'MM/dd/yyyy HH:mm:ss.fff')
-- 10/09/2018 00:58:52.557
Complete list of format specifiers is actually available in the .NET documentation . .NET文档中实际上提供了格式说明符的完整列表。
If FORMAT
function is unavailable you could simply format in a known format and use string functions to re-arrange the year, month, day and time parts. 如果
FORMAT
函数不可用,您可以简单地以已知格式进行格式化,然后使用字符串函数重新安排年,月,日和时间部分。 For example: 例如:
SELECT SUBSTRING(DateStr, 6, 2) + '/' + SUBSTRING(DateStr, 9, 2) + '/' + SUBSTRING(DateStr, 1, 4) + ' ' + SUBSTRING(DateStr, 12, 12)
FROM (
SELECT CONVERT(VARCHAR(23), GETDATE(), 126) -- ISO8601 / yyyy-mm-ddThh:mi:ss.mmm
) AS CA(DateStr)
-- 10/09/2018 01:12:50.833
SELECT CONVERT(VARCHAR(10), Date, 101) + ' ' + CONVERT(VARCHAR(12), Date, 114)
FROM (
SELECT GETDATE()
) AS CA(Date)
-- 10/09/2018 01:19:38:463
This is something that would usually be done in the presentation layer, but if you need to do it in the data layer you can use FORMAT
( documentation here ) 这通常是在表示层中完成的,但是如果需要在数据层中做到这一点,则可以使用
FORMAT
( 此处的文档 )
Syntax is: FORMAT ( value, format [, culture ] )
语法为:
FORMAT ( value, format [, culture ] )
So in your case (edited to add AM/PM designation per your comments) : FORMAT([Date & Time Added], 'dd/MM/yyy hh:mm:ss.fff tt')
因此,在您的情况下(根据您的评论进行编辑,以添加AM / PM名称) :
FORMAT([Date & Time Added], 'dd/MM/yyy hh:mm:ss.fff tt')
Custom date format string options are detailed here 自定义日期格式字符串选项在此处详细说明
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.