Get Time part from Datetime in MS SQL server


TIME PART FROM DATETIME: This article shows how to get only time part from DateTime in MS SQL Server. While development sometimes we need to take solely the Time part from the whole Datetime. That is if the given date value is  2017-01-01 09:32:15.000  and here we want to fetch only the time part for this given date that is `09:32` time as result. So mostly we developers do this part with server-side coding by using split function etc. But here we see how to get time part from DateTime in MS SQL SERVER using a simple query.


select GETDATE() as default_date,
       cast(DATEPART(HOUR,GETDATE()) as varchar(2))+':'+ cast(DATEPART(MINUTE,GETDATE()) as varchar(4)) as time_part
Output :

Get Time part from Datetime in MS SQL server Here we used the MS SQL  datepart() function to get hours and minutes and then cast it as varchar so we concatenate it, as a result finally we get only time part from a given date.

DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour, minute, etc.

In MS Sqlserver 2008 we get the time part from DateTime by using the query as follow
select GETDATE() default_date,
       cast(GETDATE() as time) time_part


Time part from DateTime in ms SQL server 2008 

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

Post Comment

Your email address will not be published. Required fields are marked *