Reputation: 475
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
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
Upvotes: -1
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
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