0

I have a column that has dates as float data type. They are in a YYYYMMDD format. I need to change these dates back into a datetime format.

I tried doing the following:

Select top 1 Date_col,CAST(FLOOR((CAST(Date_col AS numeric(10,10)))) AS DATETIME)  from dbo.table_2016

All I need is to convert the data type, but I would like to retain the formatting if possible.

3
  • Try using Convert instead. msdn.microsoft.com/en-us/library/ms187928.aspx Commented Nov 16, 2016 at 15:54
  • CAST(FLOOR(date_col) AS DATETIME)? Commented Nov 16, 2016 at 16:02
  • That was the answer on a similar question on SO. Thought I would try it. Already tried a regular "Cast" but to no avail Commented Nov 16, 2016 at 16:43

1 Answer 1

1

Try this:

select
    DATEFROMPARTS(  
        left(convert(char(8), convert(integer, Date_Col)), 4),
        substring(convert(char(8), convert(integer, Date_Col)), 5, 2),
        substring(convert(char(8), convert(integer, Date_Col)), 7, 2))
from
    table_2016;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. After running your code I realized that there is one row in my table that has a date of 0 for some reason. This was what was likely throwing up the error. Your code helped me realize that
I'm glad you got it figured out.
@Adit2789 - I think what the problem was that got fixed here, is that a date switches to float based on the number of days since the start of 1900, with the part after the decimal point representing time - your format is more like a date string changed into a number - it is actually about the year 55000 - beyond SQLs 9999 limit -

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.