使用12小时表示法格式化时间

时间:2020-09-07 01:07:28

标签: sql sql-server sql-server-2008

我已经做了一个显示日期和时间的SQL查询,时间分为小时和分钟。

select convert(varchar(10),[Date],23) as [Date], 
datepart(hour, [Time])as Hour, datepart(minute, [Time])as Minutes, 
FROM [SQLIOT].[dbo].[ZEPB_CaseLog] 

该表以24小时格式显示小时。 但是我想改成12小时格式,用一位数字加上“ 0”作为前缀。

即:01、02、03等

我想到要用大小写来做

select convert(varchar(10),[Date],23) as [Date],
case when 
datepart(hour, [Time])> 12 then (datepart(hour, [Time])- 12) as Hour
, datepart(minute, [Time])as Minutes, 
FROM [SQLIOT].[dbo].[ZEPB_CaseLog] 

这样做会给我在线带来语法错误

datepart(hour, [Time])> 12 then (datepart(hour, [Time])- 12) as Hour

--Incorrect syntax near the keyword 'as'.

我对在SQL本身中进行减法不太熟悉。我还有什么要补充的吗?

2 个答案:

答案 0 :(得分:3)

case when上存在语法错误,请尝试以下操作。

select convert(varchar(10),[Date],23) as [Date]
    , case when datepart(hour, [Time])> 12
    then (datepart(hour, [Time])- 12) 
    else datepart(hour, [Time]) End as Hour
    , datepart(minute, [Time])as Minutes, 
FROM [SQLIOT].[dbo].[ZEPB_CaseLog] 

答案 1 :(得分:0)

鉴于您对格式化(即显示)感兴趣,然后使用字符串即可。

declare @Time time = '09:33:44 pm'

select @Time [Original]
  , format(cast(@Time as datetime),N'hh') [Format Hour] -- SQL Server 2012 + (format works differently for time and datetime - datetime is required here)
  , case when len(convert(varchar(32),@Time,109)) > 17 then convert(varchar(2),@Time,109) else '0' + convert(varchar(1),@Time,109) end [Convert Hour] -- SQL Server pre-2012
  -- If you ultimatly want the hours and minutes together then do it as one
  , format(cast(@Time as datetime),N'hh\:mm') [Format hour:min] -- SQL Server 2012 + (format works differently for time and datetime - datetime is required here)
  , case when len(convert(varchar(32),@Time,109)) > 17 then convert(varchar(5),@Time,109) else '0' + convert(varchar(4),@Time,109) end [Convert hour:min] -- SQL Server pre-2012
  -- And if you want am/pm
  , format(cast(@Time as datetime),N'hh\:mm tt') [Format hour:min tt] -- SQL Server 2012 + (format works differently for time and datetime - datetime is required here)
  , case when len(convert(varchar(32),@Time,109)) > 17 then convert(varchar(5),@Time,109) else '0' + convert(varchar(4),@Time,109) end -- SQL Server pre-2012
  + case when @Time >= '12:00:00' then ' PM' else ' AM' end [Convert hour:min tt] -- SQL Server pre-2012

返回:

Original            Format Hour Convert Hour    Format hour:min Convert hour:min    Format hour:min tt  Convert hour:min tt
21:33:44.0000000    09          09              09:33           09:33               09:33 PM            09:33 PM

如果您有兴趣添加/减去日期,请使用dateadd