September 19, 2013

Extract Hour and Minute from a Date in SQL Server




Newbie database developers often spend most of their time struggling with date and time functions in SQL Server. One common requirement is extracting values out of a date like the hour and minute.

This could be done in multiple ways and differently depending on the SQL Server edition you are using

For example

in SQL Server 2005/2008

SELECT GETDATE() as "Date"
GO
SELECT CONVERT(VARCHAR(5), GETDATE(), 114) as "Hour:Minute";
GO


returns

sql-date-time
The same in SQL Server 2012 can be done using the new FORMAT functions

SELECT FORMAT(GETDATE() , 'hh:mm') as “Hour:Minute”;

Similarly as explained by Madhivanan in this post, there are several ways to format dates in various formats using the new SQL Server 2012 FORMAT functions

**Query 1**:

    SELECT FORMAT(GETDATE(),'dd-MM-yyyy') AS [dd_mm_yyyy]

**[Results]**:
    
    | DD_MM_YYYY |
    |------------|
    | 19-09-2013 |


**Query 2**:

    SELECT FORMAT(GETDATE(),'MM/dd/yyyy') AS [mm/dd/yyyy]

**[Results]**:
    
    | MM/DD/YYYY |
    |------------|
    | 09/19/2013 |


**Query 3**:

    SELECT FORMAT(GETDATE(),'MMM-yyyy') AS [MMM-yyyy]

**[Results]**:
    
    | MMM-YYYY |
    |----------|
    | Sep-2013 |


**Query 4**:

    SELECT FORMAT(GETDATE(),'MMM dd,yyyy') AS [MMM dd,yyyy]

**[Results]**:
    
    | MMM DD,YYYY |
    |-------------|
    | Sep 19,2013 |


**Query 5**:

    SELECT FORMAT(GETDATE(),'HH:mm:ss') AS [HH:mm:ss]

**[Results]**:
    
    | HH:MM:SS |
    |----------|
    | 10:02:25 |


**Query 6**:

    SELECT FORMAT(GETDATE(),'dddd, dd MMMM yyyy') AS [long format]

**[Results]**:
    
    |                 LONG FORMAT |
    |-----------------------------|
    | Thursday, 19 September 2013 |




Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

1 Response to "Extract Hour and Minute from a Date in SQL Server"
  1. Anonymous said...
    September 26, 2013 at 7:29 AM

    Excellent Post Super Tim

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions