views:

32

answers:

4

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?

+1  A: 

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.

LittleBobbyTables
why trim when you can just access the time straight away.
Pavan
@Pavan - I added the TRIM because there may be a leading space for times other than 10, 11 or 12 AM/PM. I didn't like format 108 because it doesn't include AM/PM like @Jin Yong asked for.
LittleBobbyTables
A: 

This will get the time from a datetime value and also give the am or pm add on

SELECT RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),8)),7) 

will always return the date in HH:mmAM format.

Note the lack of space

Or

SELECT REPLACE(REPLACE(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),7)),7),'AM',' AM'),'PM',' PM')

will always return the date in HH:mm AM format.

Hope that helps.

PK

Pavan
A: 

You can use the CONVERT function like this:

SELECT CONVERT(varchar, your_datetime, 108)

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

bobs
A: 

you might be able to use:

select

convert(varchar,getdate(),114)

You might be able to manually construct the query like:

string query = string.Format("INSERT INTO test (DateOnlyField, TimeOnlyField) VALUES ('{0}', '1899-12-30 {1}')", DateTime.Today.ToShortDateString(), TimeString)

I dunno if this might work to:

Create Table Schedule( ScheduleID Integer Identity, ScheduledTime DateTime )

Go

Insert Into Schedule( ScheduledTime ) Values( '10:15:00 AM' )

Go

Select ScheduledTime As DBScheduledTime, Convert( VarChar( 10 ), ScheduledTime, 114 ) As ScheduledTime

From Schedule

Go

Drop Table Schedule

Go

joshcaza
@joshcaza - Welcome to StackOverflow! A few pointers, if I may. (1) You may want to edit your post, highlight your code, and press the '101010' button, it will format the code nicely. (2) I see some C# code in there? It may be better if you provide straight SQL scripts. (3) Your output isn't in AM/PM format.
LittleBobbyTables