SQL Server Admin
T-SQL Articles

June 03, 2011

FLOOR a DateTime in SQL Server




Suppose you are given a datetime and want to emulate the FLOOR function on it eg: find first day of year, first day of month etc, you can use the following code

sqlserver-floor-date

declare @date datetime
set @date=' 2011-05-17 06:36:22.252'
select
    DATEADD(year,datediff(year,0,@date),0) as year,
    DATEADD(month,datediff(month,0,@date),0) as month,
    DATEADD(day,datediff(day,0,@date),0) as day,
    DATEADD(hour,datediff(hour,0,@date),0) as hour,
    DATEADD(minute,datediff(minute,0,@date),0) as minute,
    DATEADD(day,datediff(day,0,@date),0) +convert(varchar(15),@date,108)as seconds ,
    @date as milliseconds


In the above code, datediff finds the difference in terms of parameter (year, month, etc)
and it is added to the base date 0, which omits the month, day,time part  etc.

OUTPUT

SQL Server Floor DateTime (contd…)
image


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as an Assistant Project Manager at Ellaar Infotek Solutions Private Limited. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

 
  Feedback:

comments

0 Responses to "FLOOR a DateTime in SQL Server"
 

Copyright © 2009-2011 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions