如何只保留日期时间值的时间部分(SQL 服务器)?

How to only keep the time portion of a datetime value (SQL Server)?

这是我用来获取 HH:MM 字符串的方法:

CONVERT(varchar(5), time_requested, 108)

我认为可能有更优雅的方式,甚至可能更有效(参见 How to remove the time portion of a datetime value (SQL Server)? 上的类似问题)。

要求:

你的方法很好。它生成值的字符串表示形式。

您还可以转换为 time 数据类型:

select cast(time_requested as time)

但请注意,这是“无格式”——它包含小时、分钟、秒和秒的小数部分。所以,您的方法可能是更好的方法。

Declare @D datetime = GetDate()      -- Data Type could be Time as well

Select CONVERT(varchar(8), @D, 108)  -- for HH:MM:SS  11:27:26
Select CONVERT(varchar(5), @D, 108)  -- for HH:MM     11:27

没提到,如果2012+你也可以用Format()

Declare @D DateTime = '2016-10-22 13:30:25'

Select Format(@D,'HH:mm')         -- 13:30
Select Format(@D,'hh:mm:ss tt')   -- 01:30:25 PM