Set Birthday and get how old you are in Java

Description

The following code shows how to set Birthday and get how old you are.

Example


/*from   ww  w.  j av a 2s.  co m*/
import static java.util.Calendar.DATE;
import static java.util.Calendar.DAY_OF_WEEK;
import static java.util.Calendar.MONTH;
import static java.util.Calendar.YEAR;
import java.text.DateFormatSymbols;
import java.util.GregorianCalendar;

public class Main {
  public static void main(String[] args) {

    GregorianCalendar birthdate = new GregorianCalendar(1999, 1, 1);
    GregorianCalendar today = new GregorianCalendar(); // Today's date
    GregorianCalendar birthday = new GregorianCalendar(today.get(YEAR), birthdate.get(MONTH),
        birthdate.get(DATE));
    int age = today.get(today.YEAR) - birthdate.get(YEAR);
    String[] weekdays = new DateFormatSymbols().getWeekdays(); // Get day names
    System.out.println("You were born on a " + weekdays[birthdate.get(DAY_OF_WEEK)]);
    System.out.println("This year you " + (birthday.after(today) ? " will be " : "are ") + age
        + " years old.");
    System.out.println("In " + today.get(YEAR) + " your birthday "
        + (today.before(birthday) ? "will be" : "was") + " on a "
        + weekdays[birthday.get(DAY_OF_WEEK)] + ".");
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Date »




Date Get
Date Set
Date Format
Date Compare
Date Convert
Date Calculation
Date Parse
Timezone