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 CONVERT(VARCHAR(5), GETDATE(), 114) as "Hour:Minute";


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]

    | DD_MM_YYYY |
    | 19-09-2013 |

**Query 2**:

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

    | MM/DD/YYYY |
    | 09/19/2013 |

**Query 3**:


    | MMM-YYYY |
    | Sep-2013 |

**Query 4**:

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

    | MMM DD,YYYY |
    | Sep 19,2013 |

**Query 5**:

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

    | HH:MM:SS |
    | 10:02:25 |

**Query 6**:

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

    |                 LONG FORMAT |
    | Thursday, 19 September 2013 |

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

1 comment:

Anonymous said...

Excellent Post Super Tim