Reputation: 3494
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.
Upvotes: 1
Views: 3626
Reputation: 7692
On SQL Server side (in stored procedure, for example), you can use this kind of conversion:
declare @dt datetime2(0) = sysdatetime();
select @dt as [Date], left(convert(time(0), @dt, 108), 5) as [HH:mm];
If you need to display your data on the client side, such as a report or your app, it's better to use client' formatting capabilities. This way, you may be able to take such factors into account as preferred calendar system, 12- or 24-hour clock, etc.
Upvotes: 2
Reputation: 877
Try this, I think this is what you want.
this will give answer: 1:10
SELECT CONVERT(VARCHAR(5),CONVERT(DATETIME,'1900-01-01 01:10:00.000'),8)
You can also try this
select convert(VARCHAR,DATEPART(HOUR,'1900-01-01 01:10:00.0000000'))+':'+CONVERT(VARCHAR,DATEPART(MINUTE,'1900-01-01 01:10:00.0000000'))
Upvotes: 0
Reputation: 37313
For many format of 24H datetime length is 19 so you can use the following
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
Hope it helps
Upvotes: 0
Reputation: 729
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
Upvotes: 2