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?
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.
SELECT convert(varchar, getdate(), 108) outputs as hh:mm:ss .
You can use the CONVERT function like this:
SELECT CONVERT(varchar, your_datetime, 108)
However, this is 24-hour clock, no AM/PM.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With