Лет или года java

How do I calculate someone’s age in Java?

I want to return an age in years as an int in a Java method. What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)):

But since getYear() is deprecated I’m wondering if there is a better way to do this? I’m not even sure this works correctly, since I have no unit tests in place (yet).

Changed my mind about that: the other question only has an approximation of years between dates, not a truly correct age.

Date vs Calendar is a fundamental concept that can be gleaned from reading the Java documentation. I cannot understand why this would be upvoted so much.

@demongolem . Date & Calendar are easily understood?! No, not at all. There are a zillion Questions on the subject here on Stack Overflow. The Joda-Time project produced one of the most popular libraries, to substitute for those troublesome date-time classes. Later, Sun, Oracle, and the JCP community accepted JSR 310 (java.time), admitting that the legacy classes were hopelessly inadequate. For more info, see Tutorial by Oracle.

28 Answers 28

JDK 8 makes this easy and elegant:

public class AgeCalculator < public static int calculateAge(LocalDate birthDate, LocalDate currentDate) < if ((birthDate != null) && (currentDate != null)) < return Period.between(birthDate, currentDate).getYears(); >else < return 0; >> > 

A JUnit test to demonstrate its use:

public class AgeCalculatorTest < @Test public void testCalculateAge_Success() < // setup LocalDate birthDate = LocalDate.of(1961, 5, 17); // exercise int actual = AgeCalculator.calculateAge(birthDate, LocalDate.of(2016, 7, 12)); // assert Assert.assertEquals(55, actual); >> 

Everyone should be using JDK 8 by now. All earlier versions have passed the end of their support lives.

Читайте также:  Открытие окна поверх страницы html

In view of the fact that we are 9 years on, and in case Java 8 is used, this should be the solution to be used.

@SteveOh I disagree. I would rather not accept null s at all, but instead use Objects.requireNonNull .

Check out Joda, which simplifies date/time calculations (Joda is also the basis of the new standard Java date/time apis, so you’ll be learning a soon-to-be-standard API).

LocalDate birthdate = new LocalDate (1970, 1, 20); LocalDate now = new LocalDate(); Years age = Years.yearsBetween(birthdate, now); 

which is as simple as you could want. The pre-Java 8 stuff is (as you’ve identified) somewhat unintuitive.

EDIT: Java 8 has something very similar and is worth checking out.

EDIT: This answer pre-dates the Java 8 date/time classes and is not current any more.

@HoàngLong: From the JavaDocs: «This class does not represent a day, but the millisecond instant at midnight. If you need a class that represents the whole day, then an Interval or a LocalDate may be more suitable.» We really do want to represent a date here.

If you want to do it the way @JohnSkeet suggests, it’s like this: Years age = Years.yearsBetween(new LocalDate(getBirthDate()), new LocalDate());

@IgorGanapolsky Indeed the main difference is: Joda-Time use constructors while Java-8 and ThreetenBP use static factory methods. For a subtle bug in the way Joda-Time calculates age, please look at my answer where I have given an overview about the behaviour of different libraries.

Modern answer and overview

a) Java-8 (java.time-package)

LocalDate start = LocalDate.of(1996, 2, 29); LocalDate end = LocalDate.of(2014, 2, 28); // use for age-calculation: LocalDate.now() long years = ChronoUnit.YEARS.between(start, end); System.out.println(years); // 17 

Note that the expression LocalDate.now() is implicitly related to the system timezone (which is often overlooked by users). For clarity it is generally better to use the overloaded method now(ZoneId.of(«Europe/Paris»)) specifying an explicit timezone (here «Europe/Paris» as example). If the system timezone is requested then my personal preference is to write LocalDate.now(ZoneId.systemDefault()) to make the relation to the system timezone clearer. This is more writing effort but makes reading easier.

Please note that the proposed and accepted Joda-Time-solution yields a different computation result for the dates shown above (a rare case), namely:

LocalDate birthdate = new LocalDate(1996, 2, 29); LocalDate now = new LocalDate(2014, 2, 28); // test, in real world without args Years age = Years.yearsBetween(birthdate, now); System.out.println(age.getYears()); // 18 

I consider this as a small bug but the Joda-team has a different view on this weird behaviour and does not want to fix it (weird because the day-of-month of end date is smaller than of start date so the year should be one less). See also this closed issue.

c) java.util.Calendar etc.

For comparison see the various other answers. I would not recommend using these outdated classes at all because the resulting code is still errorprone in some exotic cases and/or way too complex considering the fact that the original question sounds so simple. In year 2015 we have really better libraries.

d) About Date4J:

The proposed solution is simple but will sometimes fail in case of leap years. Just evaluating the day of year is not reliable.

e) My own library Time4J:

This works similar to Java-8-solution. Just replace LocalDate by PlainDate and ChronoUnit.YEARS by CalendarUnit.YEARS . However, getting «today» requires an explicit timezone reference.

PlainDate start = PlainDate.of(1996, 2, 29); PlainDate end = PlainDate.of(2014, 2, 28); // use for age-calculation (today): // => end = SystemClock.inZonalView(EUROPE.PARIS).today(); // or in system timezone: end = SystemClock.inLocalView().today(); long years = CalendarUnit.YEARS.between(start, end); System.out.println(years); // 17 

Источник

Склонение возраста лет или год

Вывести на экран слово «год», «года» или «лет» в зависимости от введенного возраста
Ввести возраст человека (от 1 до 150 лет) и вывести его вместе с последующим словом «год», «года».

Составить программу, которая при вводе возраста человека от 1 до 100 выводит слова «лет» или «год» в соответствующей форме.
1)Составить программу, которая при вводе возраста человека от 1 до 100 выводит слова «лет» или.

Вывод возраста с префиксом (год, года, лет)
Привет! Подскажите как лучше решить такую проблему есть переменная $skolko_let она возвращает.

В зависимости от возраста ребёнка вывести лет, года, год
В зависимости от возраста ребёнка вывести лет, года, год. Необходимо написать код на языке VBA .

ILNAR_93, очевидно нужно выделить единицы из переданного числа и в зависимости от значения вернуть нужное

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
switch year { case 1: sYear = "год"; break; case 2: case 3: case 4: sYear = "года"; break; case 5: case 6: case 7: case 8: case 9: case 0: sYear = "лет"; break; }

Источник

Преобразование числа (лет, месяцев, дней) java

Собственно проблема в том что получаю сумму дней из определённых периодов времени. К примеру 367 — > как и этого числа получить вывод- 1 год, 0 месяцев, 2 дня. Год вывести просто а вот с остальным не могу придумать. Что бы выводило не более 12 и 30 дней/месяцев. Подскажите у кого какие мысли пожалуйста.

if (box.isSelected()) < LocalDate firstDate = LocalDate.parse(first_date_compression_start.getText(), formatter); LocalDate secondDate = LocalDate.parse(first_date_compression_end.getText(), formatter); DAYS = ChronoUnit.DAYS.between(firstDate, secondDate); result_sum.setText(DAYS + " д."); >if (box1.isSelected())

1 ответ 1

Period period = Period.between(LocalDate.now(), LocalDate.now().plusDays(367)); System.out.println("" + "Years: " + period.getYears() + "; " + "Months: " + period.getMonths() + "; " + "Days: " + period.getDays() + ";"); 
> Task :Main.main() Years: 1; Months: 0; Days: 2; 

Не так-то и просто. Результат будет зависеть от сегодяшней даты. Сравните результаты для начальной даты 1 января и 31 декабря високосного года.

@Эникейщик не то) я делаю JFX которая считает стаж работы, по этому приведение к сегодняшнему дню не подходит. Т.е. у меня 18 окон, с — по -, где я пытаюсь сделать вывод итого из заполненных окон, получилось довольно несуразно (хотя и работает) но пока могу вывести только в днях (github.com/VaSeBa/AssistantForHR).

@DmitryD не то) я делаю JFX которая считает стаж работы, по этому приведение к сегодняшнему дню не подходит. Т.е. у меня 18 окон, с — по -, где я пытаюсь сделать вывод итого из заполненных окон, получилось довольно несуразно (хотя и работает) но пока могу вывести только в днях (github.com/VaSeBa/AssistantForHR).

Источник

Ввести год рождения и определить сколько лет человеку. При выводе учитывать слова «год», «года», «лет»

Ввести год рождения и определить сколько лет человеку. При выводе учитывать слова «год», «года», «лет».

Составить программу которая при введеном количестве лет выдает сообщени вам n лет,вам n год или года
Составить программу которая при введеном количестве лет выдает сообщение вам n лет,вам n год или.

Напечатать Мне K лет, в нужных случаях слово «лет» заменяя на «год» или «года»
3. Составьте программу, которая для числа K (от 1 до 99), введенного вами, напечатает фразу «Мне K.

Ввести возраст человека (от 1 до 150 лет) и вывести его вместе с последующим словом «год», «года» или «лет»
Здравствуйте! Помогите решить задачу! Ввести возраст человека (от 1 до 150 лет) и вывести его.

Эксперт 1С

Лучший ответ

Сообщение было отмечено Евгений Шимко как решение

Решение

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
import java.util.Date; import java.util.Scanner; public class YearsOld { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int yearOfBirth = scanner.nextInt(); int yearsOld = (new Date()).getYear() + 1900 - yearOfBirth; int lastDigit = yearsOld % 10; int previousLastDigit = yearsOld / 10 % 10; if (previousLastDigit == 1) { System.out.print(yearsOld + " лет"); } else { switch (lastDigit) { case 1: System.out.print(yearsOld + " год"); break; case 2: case 3: case 4: System.out.print(yearsOld + " года"); break; default: System.out.print(yearsOld + " лет"); } } scanner.close(); } }

Правда неуверен с получением текущей даты, Eclipse пишет про устаревщий метод getYear().

Какие классы используются для работы с датами?

Источник

java — Метод для генерации постфикса к возрасту (год/года/лет)

Можно что-то отдельно выделить для себя. Например в php у фреймворка yii2 есть вот такая система:

=0 означает ноль; =1 соответствует ровно 1; one - 21, 31, 41 и так далее; few - от 2 до 4, от 22 до 24 и так далее; many - 0, от 5 до 20, от 25 до 30 и так далее; other - для всех прочих чисел (например, дробных). 

Итого, грубо говоря, на данный момент, получается так:

int age = 5; int ageLastNumber = age % 10; boolean exclusion = (age % 100 >= 11) && (age % 100 = 5 && ageLastNumber = 2 && ageLastNumber  

У итогового кода в этом ответе много недостатков. Во-первых, использование нестандартного механизма интернационализации вместо ChoiceFormat - в реальном коде эта логика потребует дополнительного покрытия тестами. Во-вторых, плохой выбор имен переменных - имя lastChar никак не соответствует типу int. В-третьих, здесь есть чисто логическая ошибка - ветвь "что-то еще" недостижима и это является хорошим признаком того, что код можно упростить.

@IvanGammel как я писал в комментарии под вопросом вопрос стоит в том, это нужно для единственной функции или всё же планируется интернационализация программы/приложения . то есть если это единственно, что планируется, то смысл от ChoiceFormat - нулевой. lastChar взята из кода автора, чтоб ему было легче ориентироваться, навигация более понятна. С else да, можно удалить. В принципе последние два момента поправил. чтоб зануды не занудствовали 😉

Источник

Оцените статью