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

前端 未结 11 1998
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:10
    SELECT CAST(CONVERT(VARCHAR,GETDATE(),102) AS DATETIME)
    
    SELECT CAST(CONVERT(VARCHAR(10),'2009-06-24 09:52:43.000',102) AS DATETIME)
    
    0 讨论(0)
  • 2021-02-13 13:12

    Strip the time, and cast it to date:

    select cast(left(yourstring, 10) as datetime)
    
    0 讨论(0)
  • 2021-02-13 13:14
    declare @originalDate datetime
    select @originalDate = '2009-06-24 09:52:43.000'
    
    declare @withoutTime datetime
    select @withoutTime = dateadd(d, datediff(d, 0, @originalDate), 0)
    
    select @withoutTime
    
    0 讨论(0)
  • 2021-02-13 13:16

    If you will always have the date in the same format, i.e. yyyy-MM-DD you can grab the first 10 characters if the value and insert that which is the equivelant of 00:00:00.0000 time for that date.

    select left('2009-12-32 4:32:00',10)
    

    This is a very efficient way to do this as it does't require converting data types HOWEVER, it does require that the date will always be formatted with a four digit year and two digit day & month.

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

    I have found that casting as a date, then to a datetime to be very efficient and intuitive.

     SELECT CAST(CAST(GETDATE() as date) as datetime)
    
    0 讨论(0)
  • 2021-02-13 13:20

    cast it to a date, and then you can use CONVERT to get just the date.

    INSERT MyTable(Column1)
    SELECT CONVERT(CHAR(8), CAST('2009-06-24 09:52:43.000' AS DATETIME), 112)
    
    0 讨论(0)
提交回复
热议问题