77

In SQL Server, how do I "floor" a DATETIME to the second/minute/hour/day/year?

Let's say that I have a date of 2008-09-17 12:56:53.430, then the output of flooring should be:

  • Year: 2008-01-01 00:00:00.000
  • Month: 2008-09-01 00:00:00.000
  • Day: 2008-09-17 00:00:00.000
  • Hour: 2008-09-17 12:00:00.000
  • Minute: 2008-09-17 12:56:00.000
  • Second: 2008-09-17 12:56:53.000
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
Portman
  • 31,785
  • 25
  • 82
  • 101

10 Answers10

115

The key is to use DATEADD and DATEDIFF along with the appropriate SQL timespan enumeration.

declare @datetime datetime;
set @datetime = getdate();
select @datetime;
select dateadd(year,datediff(year,0,@datetime),0);
select dateadd(month,datediff(month,0,@datetime),0);
select dateadd(day,datediff(day,0,@datetime),0);
select dateadd(hour,datediff(hour,0,@datetime),0);
select dateadd(minute,datediff(minute,0,@datetime),0);
select dateadd(second,datediff(second,'2000-01-01',@datetime),'2000-01-01');
select dateadd(week,datediff(week,0,@datetime),-1); --Beginning of week is Sunday
select dateadd(week,datediff(week,0,@datetime),0); --Beginning of week is Monday

Note that when you are flooring by the second, you will often get an arithmetic overflow if you use 0. So pick a known value that is guaranteed to be lower than the datetime you are attempting to floor.

Davin Studer
  • 1,501
  • 3
  • 15
  • 28
Portman
  • 31,785
  • 25
  • 82
  • 101
  • 1
    The date you calculate your offset from doesn't need to be in the past. Any date will work, provided it is itself 'FLOOR'ed to the interval in questions. If the base date is in the future, you just get a negative offset value... – MatBailie Oct 06 '09 at 16:20
  • To floor to the week use this if Sunday is the first day of the week ... select dateadd(week,datediff(week,0,@datetime),-1) – Davin Studer Jul 12 '13 at 18:30
  • Use this if Monday is the first day of the week ... select dateadd(week,datediff(week,0,@datetime),0) – Davin Studer Jul 12 '13 at 18:33
  • Not sure why this answer isn't at the top, this is a very efficient for date formatting in Microsoft SQL Server – Adam May 11 '16 at 10:58
31

In SQL Server here's a little trick to do that:

SELECT CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME)

You cast the DateTime into a float, which represents the Date as the integer portion and the Time as the fraction of a day that's passed. Chop off that decimal portion, then cast that back to a DateTime, and you've got midnight at the beginning of that day.

This is probably more efficient than all the DATEADD and DATEDIFF stuff. It's certainly way easier to type.

Chris Wuestefeld
  • 3,266
  • 2
  • 23
  • 23
  • 1
    Actually, that's 25% more characters than dateadd(day,datediff(day,0,@datetime),0), so it's not easier to type. It's also 15% less efficient. – Portman Sep 17 '08 at 19:30
  • 9
    @Portman - is there a basis for your claim it is 15% less efficient? – Hogan Jul 06 '11 at 19:54
  • 3
    casting to floor hurts performance since it will skip any datetime indexes. When using SQL 2008 it's better to use the datediff functions or CAST( [field] AS TIME) or CAST( [field] as DATE) – Rik Jan 23 '14 at 12:29
  • 1
    This doesn't work in SQL Server 2008 R2: Explicit conversion from data type date to float is not allowed. https://stackoverflow.com/a/5505975/1919692 – droid Dec 12 '19 at 20:23
  • @droid - I just tested it in SQL Server 2014, and it works fine. – Chris Wuestefeld Dec 13 '19 at 21:25
12

Expanding upon the Convert/Cast solution, in Microsoft SQL Server 2008 you can do the following:

cast(cast(getdate() as date) as datetime)

Just replace getdate() with any column which is a datetime.

There are no strings involved in this conversion.

This is ok for ad-hoc queries or updates, but for key joins or heavily used processing it may be better to handle the conversion within the processing or redefine the tables to have appropriate keys and data.

In 2005, you can use the messier floor: cast(floor(cast(getdate() as float)) as datetime)

I don't think that uses string conversion either, but I can't speak to comparing actual efficiency versus armchair estimates.

Charles Menguy
  • 40,830
  • 17
  • 95
  • 117
Moe Cazzell
  • 121
  • 1
  • 4
7

I've used @Portman's answer many times over the years as a reference when flooring dates and have moved its working into a function which you may find useful.

I make no claims to its performance and merely provide it as a tool for the user.

I ask that, if you do decide to upvote this answer, please also upvote @Portman's answer, as my code is a derivative of his.

IF OBJECT_ID('fn_FloorDate') IS NOT NULL DROP FUNCTION fn_FloorDate
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_FloorDate] (
  @Date DATETIME = NULL,
  @DatePart VARCHAR(6) = 'day'
)
RETURNS DATETIME
AS
BEGIN
  IF (@Date IS NULL)
    SET @Date = GETDATE();

  RETURN
  CASE
    WHEN LOWER(@DatePart) = 'year' THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0)
    WHEN LOWER(@DatePart) = 'month' THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0)
    WHEN LOWER(@DatePart) = 'day' THEN DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0)
    WHEN LOWER(@DatePart) = 'hour' THEN DATEADD(HOUR, DATEDIFF(HOUR, 0, @Date), 0)
    WHEN LOWER(@DatePart) = 'minute' THEN DATEADD(MINUTE, DATEDIFF(MINUTE, 0, @Date), 0)
    WHEN LOWER(@DatePart) = 'second' THEN DATEADD(SECOND, DATEDIFF(SECOND, '2000-01-01', @Date), '2000-01-01')
    ELSE DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0)
  END;
END

Usage:

DECLARE @date DATETIME;
SET @date = '2008-09-17 12:56:53.430';

SELECT
  @date AS [Now],--2008-09-17 12:56:53.430
  dbo.fn_FloorDate(@date, 'year') AS [Year],--2008-01-01 00:00:00.000
  dbo.fn_FloorDate(default, default) AS [NoParams],--2013-11-05 00:00:00.000
  dbo.fn_FloorDate(@date, default) AS [ShouldBeDay],--2008-09-17 00:00:00.000
  dbo.fn_FloorDate(@date, 'month') AS [Month],--2008-09-01 00:00:00.000
  dbo.fn_FloorDate(@date, 'day') AS [Day],--2008-09-17 00:00:00.000
  dbo.fn_FloorDate(@date, 'hour') AS [Hour],--2008-09-17 12:00:00.000
  dbo.fn_FloorDate(@date, 'minute') AS [Minute],--2008-09-17 12:56:00.000
  dbo.fn_FloorDate(@date, 'second') AS [Second];--2008-09-17 12:56:53.000
Community
  • 1
  • 1
Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
  • I suggest that you use case lower(@DatePart) when 'year'..., rather than case when lower(... to avoid all the unnecessary code and lower conversions. – N8allan Feb 08 '21 at 19:40
2

The CONVERT() function can do this as well, depending on what style you use.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 2
    We've found that CONVERT() can be anywhere from 10% to 5x less performant than dateadd/datediff. SQL imposes a penalty for converting between numeric types and strings and then back again. – Portman Sep 17 '08 at 19:32
1

There are several ways to skin this cat =)

select convert(datetime,convert(varchar,CURRENT_TIMESTAMP,101))
Leistungsabfall
  • 6,368
  • 7
  • 33
  • 41
Sean
  • 21
  • 1
1

Too bad it's not Oracle, or else you could use trunc() or to_char().

But I had similar issues with SQL Server and used the CONVERT() and DateDiff() methods, as referenced here

typicalrunt
  • 671
  • 1
  • 6
  • 12
0

DateAdd along with DateDiff can help to do many different tasks. For example, you can find last day of any month as well can find last day of previous or next month.

----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth

Source

pinaldave
  • 440
  • 6
  • 10
0

Since PostgreSQL is also a "SQL Server", I'll mention

date_trunc()

Which does exactly what you're asking gracefully.

For example:

 select date_trunc('hour',current_timestamp);
       date_trunc
------------------------
 2009-02-18 07:00:00-08
(1 row)

wogsland
  • 9,106
  • 19
  • 57
  • 93
0

For anyone looking to do this in Databricks SQL, you can do something like:

SELECT make_date(date_part('YEAR', date_field), date_part('MONTHS', date_field), 1) AS floor_date

This will convert something like '2022-10-26' to '2022-10-01'. You can also use date_part() to extract minutes and/or seconds: https://docs.databricks.com/sql/language-manual/functions/date_part.html.