Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**
     * Get the age of the user. Takes in their birthday and calculates it according to today's date
     * @param birthday Date Object
     * @return Returns an int of their age (IE 20, 55, 18). If the date is in the future, it will
     *         return -1 instead.
     */
    public static int getAge(Date birthday) {

        Calendar now = Calendar.getInstance();
        Calendar dob = Calendar.getInstance();
        dob.setTime(birthday);

        //First check for in the future:
        if (dob.after(now)) {
            return -1;
        }

        int year1 = now.get(Calendar.YEAR);
        int year2 = dob.get(Calendar.YEAR);

        int age = year1 - year2;

        int month1 = now.get(Calendar.MONTH);
        int month2 = dob.get(Calendar.MONTH);

        if (month2 > month1) {
            age--;

        } else if (month1 == month2) {
            int day1 = now.get(Calendar.DAY_OF_MONTH);
            int day2 = dob.get(Calendar.DAY_OF_MONTH);
            if (day2 > day1) {
                age--;
            }
        }

        return age;
    }
}