Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 How to set date as between one years ago and today

Author  Topic 

Sun Foster
Aged Yak Warrior

515 Posts

Posted - 2007-09-05 : 09:11:01
How to set date as 'between one years ago and today'?

I use code below but did not work:

between getdate()-365 and getdate()

Kristen
Test

22859 Posts

Posted - 2007-09-05 : 09:18:30
A year ago is:

SELECT DATEADD(Year, -1, GetDate())

but that gives you the Current Time.

If you want since midnight last night, one year ago, then you need:

SELECT DATEADD(Year, -1, DATEADD(Day, DATEDIFF(Day, 0, GetDate()), 0))

Note that 29 Feb for a leap year, subtract one year, will give you 28 Feb of the previous year. 28th Feb for the year after a leap year will give you a "previous year" of 28th Feb. Which is probably what you want, but worth just considering I suppose!

Kristen

Go to Top of Page

Kristen
Test

22859 Posts

Posted - 2007-09-05 : 09:19:02
By the by:

SELECT getdate()-365

is fine, although it doesn't take Leap years into account

Kristen
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-09-05 : 09:19:42
[code]WHERE Col1 >= DATEADD(YEAR, -1, CURRENT_TIMESTAMP)
AND Col1 < DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 1)[/code]



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -