Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

T-SQL (sql server) question

  • 12-04-2005 02:39PM
    #1
    Registered Users, Registered Users 2 Posts: 7,468 ✭✭✭


    Folks,

    I need to calculate a date, that date being a given date (getdate() below) + 1 year - 1 day. So that is:

    date + (1 year - 1 day).

    With me so far? okay. Now I have code that does this for me but is there a better way of doing it?
    declare @certYear int
    
    if (YEAR(getdate()) % 4) > 0 /* take into account leap years */
    	begin
    		select @certYear = 364
    	end
    else
    	begin
    		select @certYear = 365
    	end
    
    select getdate() + @certYear
    


Comments

  • Registered Users, Registered Users 2 Posts: 15,443 ✭✭✭✭bonkey


    Use the DATEADD function - once to add a year, once to subtract a day.

    Use it nestedly if you want to do it all on one line.

    e.g.

    select DATEADD(DATEADD(getdate(), 1, yy), -1, dd)

    (Or something like that....check books online for the correct syntax)

    jc


  • Registered Users, Registered Users 2 Posts: 7,468 ✭✭✭Evil Phil


    Thanks Bonkey, if anybody is wondering:
    select DateAdd(day, -1, DATEADD(year, 1, getdate())) 
    


  • Registered Users, Registered Users 2 Posts: 15,443 ✭✭✭✭bonkey


    Goshdurnit....had the parameters the wrong way round.

    /me hangs head in shame.

    (You're welcome though)


  • Registered Users, Registered Users 2 Posts: 2,781 ✭✭✭amen


    just as an aside a normal year has 365 days and a leap year 366!


  • Registered Users, Registered Users 2 Posts: 7,468 ✭✭✭Evil Phil


    Aye, but its a year minus one day hence 364 (for normal years) and 365 (for leap years).


  • Advertisement
Advertisement