Welcome to weblogs.com.pk Sign in | Join | Help

Date Calculations in TSQL

Sometime while implementing some date/time specific business logic; we need to do some processing on datetime data; e-g trimming away the time, knowing the start of month datetime value. Instead of converting the datetime data to string and then doing some string processing; we can use the SQL Server’ built in functions like dateadd and datediff to do the same…

select
    getdate()                                     [Now],
    datediff(dd, 0, getdate())                    [Difference in days since 0],
    dateadd(dd, datediff(dd, 0, getdate()), 0)    [Start of Today]

select
    getdate()                                     [Now],
    dateadd(mm, datediff(mm, 0, getdate()), 0)    [First day of current month],
    dateadd(wk, datediff(wk, 0, getdate()), 0)    [First day of current week],
    dateadd(hh, datediff(hh, 0, getdate()), 0)    [Start of current hour]

For more details, please read Examples of how to Calculate Different SQL Server Dates article on Database Journal

Published Wednesday, September 30, 2009 10:08 AM by khurram
Filed under: ,

Comments

No Comments

New Comments to this post are disabled