Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time format in SQL Server

Does anyone know how can I format a select statement datetime value to only display time in SQL Server?

example:

Table cuatomer
id   name   datetime
1    Alvin  2010-10-15 15:12:54:00
2    Ken    2010-10-08 09:23:56:00

When I select the table I like the result will display as below

id   name    time
1    Alvin   3:12PM
2    Ken     9:23AM

Any way that I can do it in mssql?

like image 688
Jin Yong Avatar asked Oct 07 '10 00:10

Jin Yong


People also ask

Is there time datatype in SQL?

Time is the SQL Server data type that we use to store Time. It stores the time of a day, without time zone and using 24 hours format.

How do you display time in HH MM SS in SQL?

SELECT convert(varchar, getdate(), 108) outputs as hh:mm:ss .


2 Answers

You can use the CONVERT function like this:

SELECT CONVERT(varchar, your_datetime, 108)

However, this is 24-hour clock, no AM/PM.

like image 101
bobs Avatar answered Sep 23 '22 17:09

bobs


You can use a combination of CONVERT, RIGHT and TRIM to get the desired result:

SELECT ltrim(right(convert(varchar(25), getdate(), 100), 7))

The 100 you see in the function specifies the date format mon dd yyyy hh:miAM (or PM), and from there we just grab the right characters.

You can see more about converting datetimes here.

like image 39
LittleBobbyTables - Au Revoir Avatar answered Sep 21 '22 17:09

LittleBobbyTables - Au Revoir