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
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.
Usage:
There are several ways to skin this cat =)
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.
Source
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
In SQL Server here's a little trick to do that:
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.
The CONVERT() function can do this as well, depending on what style you use.