How to get a person's birthday, knowing the date of birth of a person.

For example, his birthday is 03/12/1986, but you need to get a date of birth 03/12/2016.

Added to the task:

Print the exact date when he was 18 years old.

  • It is not clear what you need. I suppose: the day of the week this year, which is the birthday? - Sergey Gornostaev
  • his birthday is 03/12/1986, and you need to make a return 03/12/2016. this year. - Mitchell Cameron
  • In fact, on the contrary, the date of birth is a specific day of a particular year when a person was born, and a birthday is only once a year. - iksuy

4 answers 4

use calendar

Calendar c2 = Calendar.getInstance(); c2.setTime(dr); // Дата рождения c2.set(Calendar.YEAR, 2016); // год который вам нужен System.out.println(c2.getTime()); // результат 

in order to add 18 years

 Calendar c = Calendar.getInstance(); c.setTime(dr); // Дата рождения c.add(Calendar.YEAR, 18); // добавляем 18 лет System.out.println(c.getTime()); // результат 
  • one
    And what will happen from December 29? 2016 leap year - I understand your joke. - Vladislav Pyatkov
  • one
    @VladislavPyatkov will be nothing. from February 29th it will be necessary to take into account. This code will give March 1, as I know - Saidolim
  • one
    and if you change the task a little. Print the exact date he turned 18 - Mitchell Cameron

In Java 8, you can do this:

 LocalDate birthDay = LocalDate.of(1986, 3, 12); LocalDate birthDay18 = birthDay.plusYears(18); LocalDate birthDay2016 = birthDay.withYear(2016); 

    There is a fairly simple algorithm for calculating the day of the week for any date of the Gregorian calendar later than 1583. The Gregorian calendar began to operate in 1582 - immediately after October 4 it came on October 15.

    We set the year - year, month - the number of the month, the day - the day, then

    a = (14 - month) / 12 y = year - am = month + 12 * a - 2 DayNo weeks = (7000 + (day + y + y / 4 - y / 100 + y / 400 + (31 * m) / 12)) BALANCE 7 All divisions are integers (the residue is discarded).

    Result: 0 - Sunday, 1 - Monday, etc.

    link to the original day of the week calculation algorithm, by date

    • It's not entirely clear how the day of the week is related to the question? - Batanichek
    • @Batanichek what a question, such an answer ( - user205867

    I think like this:

     String happy = "12.03" Calendar c=Calendar.getInstance(); int month=c.get(c.MONTH)+1; int day=c.get(c.DAY_OF_MONTH); String date = (day+"."+month); if (happy == date) System.out.println ("С днем Рождения");