PL/SQL block, determining if year is leap year

Recommended Posts

I am just learning SQL and my assignment has the user entering their birthdate and the block will print their age and let them know if they were born in a leap year. Criteria for leap year is the year is divisible by 4 and 400 but not 100.

Here is my script below. It works fine if the year is not divisible by 100, I tested 1964 and 1989. But it shows years 1900 and 2000 as leap years.

If anyone can help, I would greatly appreciate it.

--2set serveroutput on;set verify on;DECLARE v_birthdate DATE; v_age NUMBER; V_LEAP NUMBER; begin-- get birthdate

v_birthdate := '&v_birthdate';dbms_output.put_line ('your birthdate is ' || v_birthdate);

v_age := round(months_between(sysdate,v_birthdate)/12,1);dbms_output.put_line ('your age is ' ||v_age);if mod(substr(v_birthdate,8,4),100) = 0then if mod(substr(v_birthdate,8,4),400) = 0 then DBMS_OUTPUT.PUT_LINE ('your birthyear is a leap year'); else DBMS_OUTPUT.PUT_LINE ('your birthyear is not a leap year'); end if;else if mod(substr(v_birthdate,8,4),4) = 0 then dbms_output.put_line ('your birthyear is a leap year'); else dbms_output.put_line ('your birthyear is not a leap year'); end if; end if;end;/

Share on other sites
justsomeguy    941

2000 is a leap year, so that's fine. 2000 is divisible by 400. The algorithm should be that is is a leap year if it is divisible by 400, or if it is divisible by 4 but not 100. If it's divisible by 400 it's always a leap year. If it's not divisible by 400 then it's a leap year only if it's divisible by 4 but not 100. I would re-structure your code like that, e.g.:

`if year%400 = 0 then leap yearelse if year%100 != 0 and year%4 = 0 then leap yearelse not leap year`

or:

`if year%400 = 0 or (year%100 != 0 and year%4 = 0) then leap yearelse not leap year `