Java Code for calculating Leap Year
The correct implementation is:
public static boolean isLeapYear(int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}
But if you are going to reinvent this wheel then:
public static boolean isLeapYear(int year) {
if (year % 4 != 0) {
return false;
} else if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else {
return true;
}
}
Calculate leap year in Java
If you use the GregorianCalendar
, you could do as below
Determines if the given year is a leap year. Returns true if the given
year is a leap year. To specify BC year numbers, 1 - year number must
be given. For example, year BC 4 is specified as -3.
GregorianCalendar cal = new GregorianCalendar();
if(cal.isLeapYear(year))
{
System.out.print("Given year is leap year.");
}
else
{
System.out.print("Given year is not leap year.");
}
Calculate age in java considering leap years
The correct way to do this is with the Period
and LocalDate
classes in the java.time
package. However, it seems that you're trying to reinvent the calculation for yourself.
The way that I would recommend doing this is to write a class that lets you calculate a "day number" for a given date - that is, the number of days between the specified date, and some arbitrary date in the past. Then when you want to find the number of days between two specified dates, you can just use calculate the "day number" for both dates, and subtract them.
I have done that here, for a purely Gregorian calendar. This class is no good before the Gregorian cutover - I haven't tried to build a historically accurate Julian/Gregorian hybrid calendar, such as the JDK provides. And the arbitrary date in the past that it calculates day numbers from is 31 December, 2BC. This date, of course, isn't really part of the Gregorian calendar; but for our purposes here, it doesn't matter.
Since you're unlikely to encounter any dates before the Gregorian cutover, this class should be more than adequate for your purposes. I still recommend using the Period
and LocalDate
classes instead of this one, for production code. This is just here so you can see how to do the calculations.
public class GregorianDate {
private final int day;
private final int month;
private final int year;
private static final int[] DAYS_PER_MONTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public GregorianDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public boolean isValid() {
return month >= 1 && month <= 12 && day >= 1 && day <= daysThisMonth();
}
public static int daysBetween(GregorianDate from, GregorianDate to) {
return to.dayNumber() - from.dayNumber();
}
public static int daysBetween(int fromDay, int fromMonth, int fromYear, int toDay, int toMonth, int toYear) {
return daysBetween(new GregorianDate(fromDay, fromMonth, fromYear), new GregorianDate(toDay, toMonth, toYear));
}
private int daysThisMonth() {
return (isLeapYear() && month == 2) ? 29 : DAYS_PER_MONTH[month];
}
private int dayNumber() {
return year * 365 + leapYearsBefore() + daysInMonthsBefore() + day;
}
private boolean isLeapYear() {
return ( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0;
}
private int leapYearsBefore() {
return year / 4 - year / 100 + year / 400;
}
private int daysInMonthsBefore() {
switch(month) {
case 1:
return 0;
case 2:
return 31;
default:
// Start with the number in January and February combined
int toReturn = isLeapYear() ? 60 : 59;
for (int monthToConsider = 3; monthToConsider < month; monthToConsider++) {
toReturn += DAYS_PER_MONTH[monthToConsider];
}
return toReturn;
}
}
}
Determine leap year using Java?
userInput % 4 == 0 && userInput % 100 ==0
is equivalent to userInput % 400 == 0
and userInput % 4 == 0
then it is definitely Leap year so need not to check any other condition.
Related Topics
Places Where Javabeans Are Used
How to Switch to the New Browser Window, Which Opens After Click on the Button
Eclipse Java Debugging: Source Not Found
What Are the Differences Between the Different Saving Methods in Hibernate
Java Regex Meta Character (.) and Ordinary Dot
How to Use Optional Parameters in Java
When Should We Call System.Exit in Java
How to Merge Two Sorted Arrays into a Sorted Array
Nosuchmethoderror in Javax.Persistence.Table.Indexes()[Ljavax/Persistence/Index
Getting the 'External' Ip Address in Java
In Java, How to Convert a Byte Array to a String of Hex Digits While Keeping Leading Zeros
Good Java Graph Algorithm Library
Resize an Array While Keeping Current Elements in Java