46

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-22 12:14:00.000

How can I do this? I was thinking to use DATEADD in combination with DATEPART but seems very error prone (besides performance issues)

4
  • In what way does this seem error-prone?
    – user359040
    Commented Jan 17, 2012 at 14:53
  • long and quite hard to write correctly ? :-)
    – Ghita
    Commented Jan 17, 2012 at 14:54
  • is it that you want to hide seconds?? why are you providing seconds as 000 ALWAYS?? Commented Jan 17, 2012 at 14:55
  • @Fahim I want to have 0 seconds because I want to group records from the same date/hour/minute
    – Ghita
    Commented Jan 17, 2012 at 15:16

10 Answers 10

71
SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, 0, yourcolumn), 0) FROM yourtable

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

2
  • 4
    Regarding the "Edit, best solution", casting like that will round to the nearest minute. OP wants the seconds truncated, not rounded. Example showing the rounded result: DECLARE @myDate DATETIME = '2007-05-08 12:35:32' SELECT CAST(@myDate AS smalldatetime)
    – Ojen
    Commented Feb 12, 2015 at 21:09
  • 2
    @Ojen you are absolutely right, well spotted. I removed that part of my answer Commented Feb 12, 2015 at 21:56
29

For a solution that truncates using strings try this:

SELECT CAST(CONVERT(CHAR(16), GetDate(),20) AS datetime)

CHAR(16) works only if our variable is converted to ODBC canonical format, as shown above by using 20 as the format specifier.

DECLARE @date DateTime = '2011 Nov 22 12:14:55';
SELECT CONVERT(Char(16), @date ,20) AS datetime

Results:

| datetime         |
|------------------|
| 2011-11-22 12:14 |

Then you simply cast back to a DateTime type to continue using the value.

NOTE: This is only viable for data types that do not carry TimeZone info. Also type conversions to VarChar and back are usually LESS performant than using DateTime functions that use numeric operations internally.

Consider other solutions posted if performance is a concern or if you must retain timezone information.

5
  • 11
    This isn't a good answer. First of all, CHAR(17) has to be used instead, or the minutes will be wrong. Secondly, this method produces a type conversion warning.
    – mbomb007
    Commented Nov 21, 2017 at 16:17
  • I just wasted 1 hour of work asuming this query was correct :p Thank you, internet! Commented Jan 28, 2019 at 12:37
  • 1
    This answer is correct when using the input string shown in the example. It is however not correct if the field we are operating on is a DateTime object. Commented Dec 19, 2019 at 0:56
  • It's a fairly critical weakness not to be able to cope with a datetime. The text conversion is a starting point, but we need a more general solution. And it won't let me take back my upvote. Commented Aug 17, 2020 at 14:24
  • Fellow seekers, keep scrolling to t-clausen.dk's solution below. Commented Aug 17, 2020 at 14:28
3
DECLARE @TheDate DATETIME
SET @TheDate = '2011-11-22 12:14:58.000'

DATEADD(mi, DATEDIFF(mi, 0, @TheDate), 0)

In queries

/* ...all records in that minute; index-friendly expression */ 
WHERE TheDate BETWEEN DATEADD(mi, DATEDIFF(mi, 0, @TheDate), 0) 
                  AND DATEADD(mi, DATEDIFF(mi, 0, @TheDate) + 1, 0)
2

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

2
  • 1
    DateTimeFromParts is not an effective solution. Found this Link Commented Dec 5, 2016 at 8:33
  • Thanks for the info Clausen. Commented Dec 28, 2016 at 20:29
2

With a little fiddling around, this seems to work well:

SELECT CAST(CONVERT(CHAR(17), bl.[time],113) AS varchar(17))

Result given: 2011-11-22 12:14

The exact way I'm using it in my query as part of the selection list :

,CAST(CONVERT(CHAR(17), bl.[time],113) AS varchar(17))
+ '    (UTC +0)' AS [TIME]

Gives me the result: 15 Dec 2017 06:43 (UTC +0)

1
  • ,CAST(CONVERT(CHAR(17), bl.[time],113) AS varchar(17)) is the solution to the result (15 Dec 2017 06:43) I was looking for.
    – seantunwin
    Commented Jun 17, 2019 at 17:41
2

From SQL Server 2014, You can use Format function for this.

for Ex.

 declare @Startdate datetime = '2020-11-07 15:27:50.713'

 set  @Startdate = Convert(datetime,FORMAT(@Startdate, 'yyyy-MM-dd HH:mm'))


> Result is 
2020-11-07 15:27:00.000
1
  • 1
    Nice Option. But this should be used for small tables only. In larger tables, as in my case with 10 Million Rows with Index on datetime variable, this increased the query time from 2 seconds to 23. More here: sqlperformance.com/2015/06/t-sql-queries/… Commented Apr 17, 2021 at 22:25
1

If there is no milliseconds, than

DECLARE @dt datetime2 = '2011-11-22 12:14:58.000';
DECLARE @goalDt datetime2 = DATEADD(second,-DATEPART(second,@dt), @dt);

To remove a milliseconds part, add

SET @goalDt = DATEADD(millisecond,-DATEPART(millisecond,@goalDt ), goalDt dt);
0
1

To Round Off it:

DECLARE @TheDate DATETIME;
SET @TheDate = '2019-1-2 12:14:58.400';

SELECT CAST(@TheDate AS SMALLDATETIME);

To just Truncate:

DECLARE @TruncTheDate DATETIME;
SET @TruncTheDate = '2019-1-2 12:14:58.400';

SELECT DATEADD(mi, DATEDIFF(mi, 0, @TruncTheDate), 0);
0

select substring(cast(cast(getdate() as time(0)) as char(8)),0,6)

0

SQL Server's inbuilt DATETIMEFROMPARTS function will allow you to do this by reconstructing your date from its originating parts, but with seconds and milliseconds zero'd out

DECLARE @now DATETIME = GETUTCDATE()
SELECT @now = DATETIMEFROMPARTS(DATEPART(YEAR, @now),
                                DATEPART(MONTH, @now),
                                DATEPART(DAY, @now),
                                DATEPART(HOUR, @now),
                                DATEPART(MINUTE, @now),
                                0,
                                0)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.