Link to home
Start Free TrialLog in
Avatar of Lia Nungaray
Lia NungarayFlag for United States of America

asked on

Exctract info from a date

I'm very used to the MySQL and PHP environment, but recently, I started a new job where MSSQL is the norm. I'm currently trying to figure out if there is a function similar to MySQL's date_format or PHP's date. I need to extract the month and year number from a date. For example, if I'm given Jan 2008, I would like to obtain 1-2008. Thanks!
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Select CAST(DATEPART(Month, YourDate) as varchar(2)) + '-' + CAST(DATEPART(year, YourDate) as char(4))
Avatar of wizengamot
wizengamot

The best solution would be to use the Year, Month and Day Functions.  Lets say I have a field called currentDate in my database and want to return it in the format you specified 1-2008.  Here is the code that would do that.  The cast function is required because you are building a string and values that come out of the Month,Day and Year functions are numbers and do not work well with the + operator unless casted.
SELECT currentDate, Cast(Month(currentDate) As Varchar) + '-' + Cast(Year(currentDate) As Varchar) As "NewDate" FROM myTable

Open in new window

Avatar of Lia Nungaray

ASKER

Excellent, fast and accurate!