[sql-server] Convert Time DataType into AM PM Format:

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 follows:

TableA:

            StartTime                EndTime
       ------------------         ----------------
        17:30:00.0000000          17:57:00.0000000

But I need the result as

            StartTime                EndTime
       ------------------         ----------------
            05:30 PM                 05:57 PM

When I select the table. How to get time in AM PM Format?

This question is related to sql-server sql-server-2008 select time

The answer is


SELECT CONVERT(varchar, StartTime, 100) AS ST,
       CONVERT(varchar, EndTime, 100) AS ET
FROM some_table

or

SELECT RIGHT('0'+ LTRIM(RIGHT(CONVERT(varchar, StartTime, 100),8)),8) AS ST,
       RIGHT('0'+ LTRIM(RIGHT(CONVERT(varchar, EndTime, 100),8)),8) AS ET
FROM some_table

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.

Try this:

select CONVERT(varchar(15),CAST('2014-05-28 16:07:54.647' AS TIME),100) as CreatedTime

> 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

select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),100)

almost works perfectly except for the space issue. if that were changed to:

select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),22)

...then you get the space. And additionally, if the column being converted is already of TIME format, you can skip the cast if you reference it directly.

Final answer:

select CONVERT(varchar(15),StartTime,22)

Try this:

select CONVERT(VARCHAR(5), ' 4:07PM', 108) + ' ' + RIGHT(CONVERT(VARCHAR(30), ' 4:07PM', 9),2) as ConvertedTime

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];


In SQL 2012 you can use the Format() function.

https://technet.microsoft.com/en-us/library/hh213505%28v=sql.110%29.aspx

Skip casting if the column type is (datetime).

Example:

SELECT FORMAT(StartTime,'hh:mm tt') AS StartTime
FROM TableA

This returns like 11:30 AM

select CONVERT(VARCHAR(5), FromTime, 108) + ' ' + RIGHT(CONVERT(VARCHAR(30), FromTime, 9),2)
from tablename

    select right(convert(varchar(20),getdate(),100),7)

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


Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object