Lethal_bacon
Lethal_bacon

Reputation: 63

Customizing Dates with CAST function using SQL Server

How do I get the CAST function to convert...

2011-10-30 09:32:40.000

into

10-30 

The Statement below includes the year (which I don't want)...

CAST(DateAdded AS date) AS CastToDate

There are multiple rows with different dates that will need to be converted to only show the month and day.

Upvotes: 0

Views: 50

Answers (2)

Martin Smith
Martin Smith

Reputation: 453298

Assuming you are on a reasonably modern version you can use the FORMAT function.

This is more readable than extracting a substring from the result of an operation with a cryptic numeric code.

select format(getdate(),'MM-dd')

Demo

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521389

One option would be to convert your datetime value to text using conversion mask 110, which uses the format mm-dd-yy. Then, just take the left most 5 characters, which include the month and day:

SELECT
    LEFT(CONVERT(varchar, date_col, 110), 5)
FROM yourTable;

10-30

Demo

Upvotes: 1

Related Questions