Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

E.g.

11:25 AM
14:36 PM
like image 640
Azhar Avatar asked Jul 08 '10 07:07

Azhar


People also ask

How do I get HH from datetime in SQL?

We can use DATEPART() function to get the HOUR part of the DateTime in Sql Server, here we need to specify datepart parameter of the DATEPART function as hour or hh.

How can get date and HH mm in SQL?

By using format code as 111 we can get datetime in “YYYY/MM/DD” format. By using format code as 112 we can get datetime in “YYYYMMDD” format. By using format code as 113 we can get datetime in “DD MMM YYYY HH:mm:ss: fff” format. By using format code as 114 we can get datetime in “HH:mm:ss: fff” format.


Video Answer


2 Answers

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.

like image 181
AdaTheDev Avatar answered Nov 10 '22 00:11

AdaTheDev


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.

like image 27
Andomar Avatar answered Nov 10 '22 02:11

Andomar