如何只保留datetime值的时间部分(SQL Server)? [英] How to only keep the time portion of a datetime value (SQL Server)?

查看:149
本文介绍了如何只保留datetime值的时间部分(SQL Server)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用来获取一个 HH:MM string:

Here's what I use to get a HH:MM string:

CONVERT(varchar(5), time_requested, 108)

我以为可能会有更优雅的方式,甚至可能更有效率(参见如何删除datetime值的时间部分(SQL Server)?)。

I'm thinking there may be a more elegant way, even maybe more efficient (see similar question on How to remove the time portion of a datetime value (SQL Server)?).

要求:


  • 最终结果必须轻松转换为字符串(为了能够连接一些字段 time_created 包含 date_created 等字段。

  • 必须涵盖以下2种情况: HH:MM HH:MM:SS

  • the final result has to be easily convertible to a string (in order to be able to concatenate some field time_created with a field such as date_created).
  • the following 2 cases must be covered: HH:MM and HH:MM:SS.

推荐答案

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()

Failed to mention, if 2012+ you could also use 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

这篇关于如何只保留datetime值的时间部分(SQL Server)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆