1

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
A.Goutam
  • 3,422
  • 9
  • 42
  • 90
  • you do realize that both statement are not equal. [1] is to convert datetime to string using style 8. [2] is to convert string to string using style 8 – Squirrel Nov 12 '16 at 08:10

4 Answers4

2

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

James
  • 729
  • 6
  • 10
2

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.

Roger Wolf
  • 7,307
  • 2
  • 24
  • 33
0

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

Hadi
  • 36,233
  • 13
  • 65
  • 124
0

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'))
mansi
  • 837
  • 5
  • 12