在没有AM / PM的情况下将时间转换为12小时格式

时间:2017-03-08 11:09:10

标签: sql-server database sql-server-2014

我想从MSSQL 2014中提取日期时间数据,仅显示12小时格式且没有AM / PM。我已尝试通过互联网建议的所有内容如下:

time_adm = convert(varchar(15), CAST(hadmlog.admdate AS TIME), 100), --//2:30PM

我也尝试了format()但是它返回了一个错误"轻量级池...等不支持公共语言运行时(CLR)执行"

time_adm22 = FORMAT(CAST(hadmlog.admdate AS DATETIME),'hh:mm') --error

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情

DECLARE @tbl TABLE(SomeDate DATETIME);
INSERT INTO @tbl VALUES({ts'2017-01-01 07:13:52'}),({ts'2017-01-01 17:13:52'})

SELECT t.SomeDate
      ,a.FormattedTime
      ,LEFT(a.FormattedTime,PATINDEX('%[a,p]m',a.FormattedTime)-1) 
FROM @tbl AS t
CROSS APPLY(SELECT CONVERT(VARCHAR(20),CAST(t.SomeDate AS TIME),100) AS FormattedTime) AS a

结果

SomeDate                    FormattedTime   YourOutput
2017-01-01  07:13:52.000    7:13AM          7:13
2017-01-01  17:13:52.000    5:13PM          5:13

答案 1 :(得分:0)

您可以尝试使用字符串Replace来消除AM和PM:

select hadmlog.admdate,
    REPLACE(REPLACE(convert(varchar(7), CAST(hadmlog.admdate AS Time) , 100),'AM',''),'PM','') as Converted
from hadmlog