A way to extract from a DateTime value data without seconds

前端 未结 8 2024
一向
一向 2020-11-30 13:39

I have an sql DateTime (ms sql server) and want to extract the same date without the seconds: e.g. 2011-11-22 12:14:58.000 to become: 2011-11

相关标签:
8条回答
  • 2020-11-30 14:14

    Date and time needs carefully and not being converted as TEXT.

    My personal solution:

        CREATE FUNCTION [dbo].[fnDateTimeTruncated]
    (
        @datetime DATETIME
    )
    RETURNS DATETIME
    AS
    BEGIN
        RETURN DATETIMEFROMPARTS ( year(@datetime), month(@datetime), day(@datetime), DATEPART(hh,@datetime), DATEPART(mi,@datetime), 0, 0)
    END
    

    Edited:

    Regarding http://blog.waynesheffield.com/wayne/archive/2012/03/truncate-a-date-time-to-different-part/, DateAdd has a better performance. Thanks to t-clausen.dk

    0 讨论(0)
  • 2020-11-30 14:18
    SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, 0, yourcolumn), 0) FROM yourtable
    

    This will be effective, if you don't want a slow conversion between datatypes.

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