Get hour:minutes from DATETIME2

时间:2016-11-12 05:57:01

标签: sql-server tsql sql-server-2008-r2 datetime2

I have a problem in SQL Server 2008 R2. I want to get HH:mm from a DATETIME2 column. When I write this statement:

SELECT CONVERT(VARCHAR(5), getdate(), 8)

I am getting perfect result that is 11:19, but when I try to get time from:

SELECT (CONVERT(VARCHAR(5), '1900-01-01 01:10:00.0000000', 8))

I am getting result 1900 but I need 01:10.

How can I get the result from this statement? I know there there are multiple questions/answers like this but I have not found any answer that matches my question.

4 个答案:

答案 0 :(得分:1)

Try this:

SELECT RIGHT('0' + CONVERT(VARCHAR(2), 
DATEPART(HOUR, '1900-01-01 01:10:00.0000000')), 2) hh, 
DATEPART(minute, '1900-01-01 01:10:00.0000000') mm

Or

SELECT LEFT(CONVERT(TIME(0), '1900-01-01 01:10:00.0000000'), 2) hh , DATEPART(minute, '1900-01-01 01:10:00.0000000') mm

答案 1 :(得分:1)

在SQL Server端(例如,在存储过程中),您可以使用这种转换:

declare @dt datetime2(0) = sysdatetime();

select @dt as [Date], left(convert(time(0), @dt, 108), 5) as [HH:mm];

如果您需要在客户端显示数据,例如报告或应用,最好使用客户端的格式化功能。这样,您可以将这些因素考虑为首选日历系统,12小时制或24小时制等。

答案 2 :(得分:0)

对于24H日期时长度的许多格式为19,因此您可以使用以下

 SELECT RIGHT('0' + CAST(DATEPART(HOUR, Substring('1900-01-01 01:10:00.0000000',1,19)) AS VARCHAR(2)), 2) + ':' + CAST(DATEPART(minute, substring('1900-01-01 01:10:00.0000000',1,19)) AS VARCHAR(2)) HHmm

希望有所帮助

答案 3 :(得分:0)

试试这个,我想这就是你想要的。

这将给出答案:1:10

SELECT CONVERT(VARCHAR(5),CONVERT(DATETIME,'1900-01-01 01:10:00.000'),8)

你也可以尝试这个

select convert(VARCHAR,DATEPART(HOUR,'1900-01-01 01:10:00.0000000'))+':'+CONVERT(VARCHAR,DATEPART(MINUTE,'1900-01-01 01:10:00.0000000'))