Converting a numeric value to date time

流过昼夜 提交于 2020-01-02 04:46:28

问题


I am working in SQL Server 2012. My date column in a data set looks like this: 41547. The column is in nvarchar (255). I want to convert it to something like this: yyyy-mm-dd hh:mm:ss (Example: 2013-09-14 12:23:23.98933090). But I can not do this. I am using following code:

select convert(datetime, date_column, 6)

But this is giving following error:

Msg 241, Level 16, State 1, Line 1 Conversion failed when converting
date and/or time from character string.

What am I doing wrong?


回答1:


Your date is actually a numeric value (float or integer), stored in a char column. So, you need to convert it to a numerical value (in this case, to float) first, like:

select convert(datetime, CONVERT(float,date_column))

A value of 41547.5 will result in:

`2013-10-02 12:00:00`

The style argument, in your case 6 is only necessary when converting from or to char-types. In this case it is not needed and will be ignored.


NB: The float value is the number of days since 1900-01-01.

e.g. select convert(datetime, CONVERT(float,9.0)) => 1900-01-10 00:00:00; the same as select dateadd(day,9.0,'1900-01-01') would.

The decimal part of the number also equates to days; so 0.5 is half a day / 12 hours.

e.g. select convert(datetime, CONVERT(float,.5)) => 1900-01-01 12:00:00. (Here our comparison to dateadd doesn't make sense, since that only deals with integers rather than floats).




回答2:


There is an easier way to do it as well.

select convert(date,cast (date_Column+ 19000000 as nvarchar(10)))
    as date_Column_Formated
  from table_Name



回答3:


I have just found the way to do this.

First I have to covert the nvarchar to int then I have to convert it to date time. I have used following code:

Select convert(datetime, (convert (int, [date_column])), 6) as 'convertedDateTime' from mytable



回答4:


6 format is: "dd mon yy" Like this: SELECT convert(datetime, '23 OCT 16', 6) Other formats will cause your error




回答5:


SELECT CONVERT(DATETIME,CONVERT(INT,date_column))


来源:https://stackoverflow.com/questions/19271007/converting-a-numeric-value-to-date-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!