How to convert datetime to date only (with time set to 00:00:00.000)

前端 未结 11 1999
Happy的楠姐
Happy的楠姐 2021-02-13 12:42

I have a string \'2009-06-24 09:52:43.000\', which I need to insert to a DateTime column of a table.

But I don\'t care about the time, just want to insert it as 2009-06-

相关标签:
11条回答
  • 2021-02-13 13:20

    A variety of hacks:

    • Convert your string to a datetime, then back again using the optional "style" parameter to convert to convert your datetime to a string using just the date portion
    • use substring to chop off the end
    • round the datetime using floor
    0 讨论(0)
  • 2021-02-13 13:20

    For SQL Server 2005 and below:

    CONVERT(varchar(8), @ParamDate, 112)    -- Supported way
    
    CAST(FLOOR(CAST(@ParamDate AS float)) AS DATETIME)   -- Unsupported way
    

    For SQL Server 2008 and above:

    CAST(@ParamDate AS DATE)
    
    0 讨论(0)
  • 2021-02-13 13:27

    James is correct. If you're starting off with a string, and the format will always be what you say it is, then you keep it simple and efficient. Use LEFT( @StrDate, 10) and CONVERT that to your datetime value. Done.

    If your input string could be any valid date/time format, then you have to use CONVERT(datetime, @StrDate) first. After that you go with what Bing just said to strip off the time part.

    0 讨论(0)
  • 2021-02-13 13:28

    Probably a cleaner and more portable way to do this, but my years old idiom is:

    insert into tbl (date_column)
    select convert(varchar, convert (datetime, '2009-06-24 09:52:43.000'), 101)
    
    0 讨论(0)
  • 2021-02-13 13:35

    An enhancement to the unsupported version: I am not sure if this may effect any performance. getdate() is an input timestamp in my query.

    select cast(cast(getdate() as DATE) as DATETIME)

    0 讨论(0)
提交回复
热议问题