views:

234

answers:

4

How to get time part from Sql Server 2005 datetime in HH:mm tt format

e.g. 11:25 AM

14:36 PM

A: 

You need to use CONVERT function:

CONVERT(VARCHAR, yourdatetimefiled, 114) AS [HH:MI(12H)]
Anax
According to MSDN, 114 = `hh:mi:ss:mmm(24h)`.
Oded
but I want in HH:mm tt format and it does not provide tt info like AM or PM
Azhar
I wrote the answer by heart since I don't have MSSQL access at the moment. I believe AdaTheDev got it right.
Anax
+3  A: 

One way is:

SELECT LTRIM(RIGHT(CONVERT(VARCHAR(20), GETDATE(), 100), 7))

If you have a look at Books Online here, format 100 is the one that has the time element in the format you want it in, it's just a case of stripping off the date from the front.

AdaTheDev
This will print 8:00 PM, but I think the question is looking for 20:00 PM
Andomar
@Andomar - good point. If that is really what is needed, I'd argue the AM/PM is irrelevant and suggest a more conciser approach though
AdaTheDev
A: 
select right(convert(char(20),getdate(),0),7)

No check though

Salil
+1  A: 

You'll need two converts, one to get the HH:mm time, and one to get AM/PM. For example:

declare @date datetime
set @date = '20:01'
SELECT CONVERT(VARCHAR(5), @date, 108) + ' ' +
       SUBSTRING(CONVERT(VARCHAR(19), @date, 100),18,2)

This prints:

20:01 PM

In a select query, replace @date with your column's name.

Andomar