Dynamic date on Leap Year

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • benchpolo
    New Member
    • Sep 2007
    • 142

    Dynamic date on Leap Year

    I'm trying to write a code that will pick-up the end of the previous month, but I encountered a road block when the month such as February is a leap year. 2011 has 28 days and 2012 has 29 days. Trying to figure out how to incorporate leap year in the code below:

    Code:
    DateAdd(day, -1, DateAdd(month, DateDiff(month, 0, GETDATE())+1, 0))
    Thanks.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Code:
    DateAdd(day, -1, CONVERT(VARCHAR(2), Month(GETDATE())) + '/01/' + CONVERT(VARCHAR(4), YEAR(GETDATE())))

    Comment

    • ck9663
      Recognized Expert Specialist
      • Jun 2007
      • 2878

      #3
      Here is a list of how to find specific dates in SQL Server.

      Happy Coding!!!


      ~~ CK

      Comment

      • PsychoCoder
        Recognized Expert Contributor
        • Jul 2010
        • 465

        #4
        If you're trying to determine if it's a leap year then you can use a user defined function. Here's an example on finding if the provided date is a leap year

        Code:
        CREATE FUNCTION dbo.udfIsLeapYear(@date DATETIME)
        RETURNS BIT
        AS
        BEGIN
        
            IF (YEAR(@date) % 4 = 0 AND YEAR(@date) % 100 != 0) OR
                YEAR(@date) % 400 = 0
                RETURN 1
        
            RETURN 0
        
        END
        GO

        Comment

        • ck9663
          Recognized Expert Specialist
          • Jun 2007
          • 2878

          #5
          Here's a simpler one using a built-in-function.


          Happy Coding!!!

          ~~ CK

          Comment

          • PsychoCoder
            Recognized Expert Contributor
            • Jul 2010
            • 465

            #6
            @ck9663 I don't see how that is simpler than the UDF I provided?

            Comment

            • ck9663
              Recognized Expert Specialist
              • Jun 2007
              • 2878

              #7
              I guess it depends on how you look at it.

              IsDate is a sql-server date function that returns 1 if the expression you are testing is a valid date and 0 if it is not. No need to build a function.

              To illustrate:

              Code:
              select 
              IsValidDate_20120229 = isdate('02/29/2012'), 
              IsValidDate_20130229 = isdate('02/29/2013')
              and you will have this result

              Code:
              IsValidDate_20120229 IsValidDate_20130229 
              -------------------  --------------------
              1                    0
              I just think using a built-in function is simpler than creating a new one with case statements.


              Happy Coding!!!


              ~~ CK

              Comment

              Working...