Heartcroft
Heartcroft

Reputation: 1712

Retrieveing Day, Month and Year separately from Date

Is there an implemented way to retrieve separately day, month and year from a Date field in T-SQL? Everything I've found is to make the process the other way around, in my case I mean if I have 2012-05-22 I would like to have 3 different methods to get as a result 2012, 05 and 22 respectively.

Thanks in advance.

Upvotes: 0

Views: 15861

Answers (3)

Mathew Thompson
Mathew Thompson

Reputation: 56459

If it's SQL Server, you can use DATEPART (MSDN: http://msdn.microsoft.com/en-us/library/ms174420.aspx)

Example:

DECLARE @yourDate DATETIME
SET @yourDate = '2012-05-22'

SELECT DATEPART(DAY, @yourDate), 
       DATEPART(MONTH, @yourDate),
       DATEPART(YEAR, @yourDate)

Upvotes: 4

Arion
Arion

Reputation: 31249

If you are using mssql. You can do this:

DECLARE @date DATETIME
SET @date=GETDATE()
SELECT
    YEAR(@date) AS Years,
    MONTH(@date) AS MONTHs,
    DAY(@date) AS Days

Or you can use datepart. Like this:

DECLARE @date DATETIME
SET @date=GETDATE()
SELECT
    DATEPART(YEAR,@date) AS Years,
    DATEPART(MONTH,@date) AS MONTHs,
    DATEPART(DAY,@date) AS Days

Upvotes: 1

dannymcc
dannymcc

Reputation: 3824

I believe you can do date_format(DATEFIELD %M) as month, date_format(DATEFIELD %b) as day.

I've used something similar in a Rails application.

http://www.w3schools.com/sql/func_date_format.asp

Upvotes: 0

Related Questions