I have one Table which has two fields such as \"StartTime\" and \"EndTime\". The DataType of the Two columns are Time.
So the Values of the Table looks like as follo
> SELECT CONVERT(VARCHAR(30), GETDATE(), 100) as date_n_time
> SELECT CONVERT(VARCHAR(20),convert(time,GETDATE()),100) as req_time
> select convert(varchar(20),GETDATE(),103)+' '+convert(varchar(20),convert(time,getdate()),100)
> Result (1):- Jun 9 2018 11:36AM
> result(2):- 11:35AM
> Result (3):- 06/10/2018 11:22AM
Multiple functions, but this will give you what you need (tested on SQL Server 2008)
Edit: The following works not only for a time
type, but for a datetime
as well.
SELECT SUBSTRING(CONVERT(varchar(20),StartTime,22), 10, 11) AS Start, SUBSTRING(CONVERT(varchar(20),EndTime,22), 10, 11) AS End FROM [TableA];
Here are the various ways you may pull this (depending on your needs).
Using the Time DataType:
DECLARE @Time Time = '15:04:46.217'
SELECT --'3:04PM'
CONVERT(VarChar(7), @Time, 0),
--' 3:04PM' --Leading Space.
RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7),
--' 3:04 PM' --Space before AM/PM.
STUFF(RIGHT(' ' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' '),
--'03:04 PM' --Leading Zero. This answers the question above.
STUFF(RIGHT('0' + CONVERT(VarChar(7), @Time, 0), 7), 6, 0, ' ')
--'03:04 PM' --This only works in SQL Server 2012 and above. :)
,FORMAT(CAST(@Time as DateTime), 'hh:mm tt')--Comment out for SS08 or less.
Using the DateTime DataType:
DECLARE @Date DateTime = '2016-03-17 15:04:46.217'
SELECT --' 3:04PM' --No space before AM/PM.
RIGHT(CONVERT(VarChar(19), @Date, 0), 7),
--' 3:04 PM' --Space before AM/PM.
STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' '),
--'3:04 PM' --No Leading Space.
LTRIM(STUFF(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), 6, 0, ' ')),
--'03:04 PM' --Leading Zero.
STUFF(REPLACE(RIGHT(CONVERT(VarChar(19), @Date, 0), 7), ' ', '0'), 6, 0, ' ')
--'03:04 PM' --This only works in SQL Server 2012 and above. :)
,FORMAT(@Date, 'hh:mm tt')--Comment line out for SS08 or less.
Using @Saikh's answer above, the 2nd option, you can add a space between the time itself and the AM or PM.
REVERSE(LEFT(REVERSE(CONVERT(VARCHAR(20),CONVERT(TIME,myDateTime),100)),2) + ' ' + SUBSTRING(REVERSE(CONVERT(VARCHAR(20),CONVERT(TIME,myDateTime),100)),3,20)) AS [Time],
Messy I know, but it's the solution I chose. Strange that the CONVERT() doesn't add that space automatically. SQL Server 2008 R2
Try this:
select CONVERT(varchar(15),CAST('2014-05-28 16:07:54.647' AS TIME),100) as CreatedTime
This returns like 11:30 AM
select CONVERT(VARCHAR(5), FromTime, 108) + ' ' + RIGHT(CONVERT(VARCHAR(30), FromTime, 9),2)
from tablename