1

I have date column in my table as string type example Feb-18. How do I change it to date type as 01-02-2018?

2
  • Do you want to change the actual column data type or just convert the string into a date in a SELECT statement? Commented Mar 12, 2020 at 11:24
  • 1
    Storing dates as string, storing 2 digit years, assuming a language - all big problems. Commented Mar 12, 2020 at 11:51

3 Answers 3

6

Use convert() with add one day :

select convert(date, '01-' + 'Feb-18')
Sign up to request clarification or add additional context in comments.

Comments

5

SQL Server is pretty good about figuring out dates. But you need a day, so:

select convert(date, '01-' + datecol)

Note: You should be very careful about storing dates as strings. I would recommend that you test the conversion to be sure it works for all values:

select datecol
from t
where try_convert(date, '01-' + datecol) is null and
      datecol is not null;

If this returns any rows, then you have bad dates in your data. Oh, it would have been better to catch these by rejecting the insert/updates in the first place. However, you might be able to figure out how to fix them.

Comments

0

You can also try the following way.

Select try_cast('01-' + 'Feb-18' as Date) as [String To Date]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.