在 java 年龄计算 returns 错误值
In java age calculate returns wrong value
In java I want to calculate age..
我正在使用 "jodatime.jar"
LocalDate today = LocalDate.now();
LocalDate birthdate = new LocalDate ("1990-12-12");
Years age = Years.yearsBetween(birthdate, today);
我想要年龄 integer
..这里 returns 值像 P25Y..如何获得年龄的整数值..我只想要25
有没有其他方法可以在 java 中使用日期格式获取年龄...在 google 中我尝试了很多但没有找到任何使用 日期格式的合适示例
使用 joda-time
您可以使用 Period 在 joda time
api 中实现此功能。尝试这样的事情:
Period period = new Period(d1, d2);// d1,d2 are Date objects
System.out.print("You are " + period.getYears() + " years old");
使用java.time
如果你能用java.time classes LocalDate
and Period
进入Java8或更高版本,那么它可以这样实现:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1990, Month.DECEMBER, 12);
Period p = Period.between(birthday, today);
System.out.println("You are " + p.getYears() + " years old");
输出
You are 25 years old
您可以使用 age.getYears()
。来自doc
Gets the number of years that this period represents.
age
不是 Integer
,而是 Years
。如果要以整数形式检索年龄,请使用 getYears()
方法:
int age = Years.yearsBetween(birthdate, today).getYears();
如果你想继续使用 jodattime,你应该知道,它有一个获取年数的方法:.getYears()
如果你只想获取年龄,那么使用公历获取年份并将其与当前年份进行比较:
Calendar date = new GregorianCalendar(2012, 9, 5);
int birthyear = date.get(Calendar.YEAR); // 2012
Date currdate = new Date();
Calendar date2 = new GregorianCalendar();
date2.setTime(currdate);
int curryear = date.2get(Calendar.YEAR); // current year(2015 atm)
使用age.getYears()
得到年龄的int
值。
In java I want to calculate age..
我正在使用 "jodatime.jar"
LocalDate today = LocalDate.now();
LocalDate birthdate = new LocalDate ("1990-12-12");
Years age = Years.yearsBetween(birthdate, today);
我想要年龄 integer
..这里 returns 值像 P25Y..如何获得年龄的整数值..我只想要25
有没有其他方法可以在 java 中使用日期格式获取年龄...在 google 中我尝试了很多但没有找到任何使用 日期格式的合适示例
使用 joda-time
您可以使用 Period 在 joda time
api 中实现此功能。尝试这样的事情:
Period period = new Period(d1, d2);// d1,d2 are Date objects
System.out.print("You are " + period.getYears() + " years old");
使用java.time
如果你能用java.time classes LocalDate
and Period
进入Java8或更高版本,那么它可以这样实现:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1990, Month.DECEMBER, 12);
Period p = Period.between(birthday, today);
System.out.println("You are " + p.getYears() + " years old");
输出
You are 25 years old
您可以使用 age.getYears()
。来自doc
Gets the number of years that this period represents.
age
不是 Integer
,而是 Years
。如果要以整数形式检索年龄,请使用 getYears()
方法:
int age = Years.yearsBetween(birthdate, today).getYears();
如果你想继续使用 jodattime,你应该知道,它有一个获取年数的方法:.getYears()
如果你只想获取年龄,那么使用公历获取年份并将其与当前年份进行比较:
Calendar date = new GregorianCalendar(2012, 9, 5);
int birthyear = date.get(Calendar.YEAR); // 2012
Date currdate = new Date();
Calendar date2 = new GregorianCalendar();
date2.setTime(currdate);
int curryear = date.2get(Calendar.YEAR); // current year(2015 atm)
使用age.getYears()
得到年龄的int
值。