John
John

Reputation: 475

How do i show just the time with AM or PM from a field that is a datetime format?

I have a column of data in SQL that is currently in the datetime format. It can be changed if needed. I need to show just the time of day, to the 10th of a second, with either AM or PM attached also. I do not want the date to be shown in this instance.

So instead of '1900-01-01 11:45:59.800' as an example, i need '11:45:59.8 AM'.
Also, this is not a current "getdate" time. It is from a field of data i have called 'Time' I see all sorts of convert formats on the web, but none will pull this up for me.

Thank you!!!!

Upvotes: 2

Views: 21710

Answers (3)

Annapoorani KS
Annapoorani KS

Reputation: 1

I think this will work if you want to get in HH:MM format

SELECT
  RIGHT(CONVERT(VARCHAR(26), GETDATE(), 117), 14)

You can also refer to this page for more formats

http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36271.1570/html/blocks/X41864.htm

Upvotes: -1

Tony
Tony

Reputation: 10327

Rename your table field, Time is a reserved word and it will be a pain to maintain. Make sure you are using the new datetime2 data type if you want millisecond accuracy.

To format the time part use:

SELECT CONVERT(TIME, [Time]) FROM [Your Table]

If you only want a three digits after the period you can use:

SELECT CONVERT(TIME(3), [Time]) FROM [Your Table] 

Upvotes: 1

MatBailie
MatBailie

Reputation: 86715

As in my comment, I'd advise you to not do this.

SQL Server is a place for data, and converting the data for display purposes is often a blurring of the lines that can come back to haunt you. (One example; what if you need that time as a Time somewhere else in the future. Are you going to convert it back from a string again?)

If it is Necessary, then you have to do some of the formatting yourself.

SELECT
  RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109), 14)

Or, more messy...

SELECT
  DATEPART(HOUR, GETDATE()) + ':' +
  DATEPART(MINUTE, GETDATE()) + ':' +
  DATEPART(SECOND, GETDATE()) + '.' +
  DATEPART(MILLISECOND, GETDATE()) +
  CASE WHEN DATEPART(HOUR, GETDATE()) < 12 THEN 'AM' ELSE 'PM' END


Did I say? You're better doing it on the client side ;)

Upvotes: 9

Related Questions