Datetime format

  • Hi all,

    Declare @date datetime= '18-06-2014 11:38:46.050'

    select cast(@date as varchar)

    Message: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

    Declare @date datetime= '2014-06-18 11:40:04.753'

    select cast(@date as varchar)

    Output: Jun 18 2014 11:40AM

    How can I convert different datetime format to a common datetime format so that it can work for different time formats/

    _______________________________________________________________
    To get quick answer follow this link:
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

  • You are trying to store the value 18 in a month, which is not possible of course.

    You can either use CONVERT to convert the string to a datetime. You only need to specify the correct format.

    DECLARE @date DATETIME= CONVERT(DATETIME,'18-06-2014 11:38:46.050',105); -- apparently the Italian format

    SELECT CAST(@date AS VARCHAR);

    Or you can use SET DATEFORMAT to override the implicit date formatting.

    SET DATEFORMAT dmy;

    DECLARE @date DATETIME= '18-06-2014 11:38:46.050';

    SELECT CAST(@date AS VARCHAR);

    Need an answer? No, you need a question
    My blog at https://sqlkover.com.
    MCSE Business Intelligence - Microsoft Data Platform MVP

  • Also

    kapil_kk (6/18/2014)


    select cast(@date as varchar)

    Don't declare or cast varchars without a length definition. The default will bite you sooner or later.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply