SQL Server: Extracting JUST Time From Datetime Value

Tonight I found myself needing to extract just the time from a datetime column in SQL Server 2000. After a bit of Googling, it became clear that there are about 1 million articles on how to extract just the date from a datetime, but not very many articles taking about just getting time. For reference, this is how I ended up doing it.

In MS SQL, the convert function is very handy for dealing with dates. There are a number of different conversion styles it supports:
http://www.w3schools.com/sql/func_convert.asp

 SELECT CONVERT(VARCHAR,getdate(),108)

This tells SQL Server to convert the current date/time into a varchar using style 108, which is "hh:mm:ss".

The most common conversion style I use is probably 101, or "mm/dd/yy".

There are a couple of annoying things about convert. One is that is returns a string. This means that if you want to keep doing date manipulations you usually have to cast it back to a datetime one way or another. I guess technically ColdFusion's dateformat function returns a string, but CF (being typeless) is better as auto-casting those strings back into dates when it can. The other main annoyance is that we just have about 19 preset date/time formats to choose from. I guess ColdFusion spoils us with masks that give us full control.

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Syed Tayyab Ali's Gravatar Good stuff...
# Posted By Syed Tayyab Ali | 7/14/09 1:01 PM
Drew's Gravatar What causes the query to return '1901/01/01 21:38:45.000' when it should only return '21:38:45' ???
# Posted By Drew | 1/8/10 12:09 PM
Brad Wood's Gravatar @Drew: That will only happen if you cast the string that the convert function returns BACK to a datetime data type. I'm actually not sure why the year defaults to 1901 since I'm pretty sure SQL Server's epoch date is 1/1/1970. You will notice that SELECT cast('' as datetime) produces "1900-01-01 00:00:00.000".

If you are on SQL Server 2008 you can use the new TIME data type.
# Posted By Brad Wood | 1/8/10 11:05 PM
urjo's Gravatar Awesome information...just what I needed!
# Posted By urjo | 3/5/10 9:26 AM
Purvi's Gravatar It really helped me.
# Posted By Purvi | 3/11/10 7:37 AM
aparna's Gravatar Good Stuff.
# Posted By aparna | 6/17/10 9:20 AM


BlogCFC was created by Raymond Camden. This blog is running version 5.9.5. Contact Blog Owner