When I select time in SQL it is returned as 2011-02-25 21:17:33.933. But I need only the time part. How can I do this? I'm trying to: order by "Onlie Duration" DESc , but need it to be ordered by time
Asked
Active
Viewed 1,108 times
0
-
Possible duplicate of [How to get Time from DateTime format in SQL?](https://stackoverflow.com/questions/7710449/how-to-get-time-from-datetime-format-in-sql) – Jamiec Sep 04 '19 at 15:52
-
So you don't care about the date portion? So a date of '2019-01-01 09:00:00' would be sorted before '2015-01-01 09:01:00'? – Sean Lange Sep 04 '19 at 15:54
3 Answers
4
You can do something like this:
SELECT time_column FROM dbo.table
ORDER BY CONVERT(time, time_column)

Joao Leal
- 5,533
- 1
- 13
- 23
0
Use Convert function
SELECT * FROM MyTable
ORDER BY CONVERT(varchar(10), TimeField, 108)
UPD Or using DATEDIFF:
SELECT * FROM MyTable
ORDER BY DATEDIFF(MILLISECOND, CAST(TimeField AS DATE), TimeField)

tgralex
- 794
- 4
- 14
-
Not sure that varchar is the best idea...would work with time but not a good habit to sort datetime type of data as characters. – Sean Lange Sep 04 '19 at 15:58
-
using DATEDIFF is probably the best way of doing it without any conversion. See Updated portion. – tgralex Sep 04 '19 at 17:01
0
You can get only the time part using:
select convert(char,[YourDateColumn],108) from [YourTable]
Sorting your data based on time can be done by ordering using:
select * from [YourTable] order by convert(char,[yourDateColumn],108)
The downside to this is that, sorting with just the time when there are dates for different days will mix the time for the various days.

Bamidelzz
- 76
- 1
- 2