从 BirthDate 计算年龄
Posted
技术标签:
【中文标题】从 BirthDate 计算年龄【英文标题】:Calculate age from BirthDate 【发布时间】:2016-12-22 09:17:40 【问题描述】:我有 DatePicker 对话框,当我当时选择日期时,我想计算它的工作年龄,但是当我选择当年的日期时,它显示 -1 年龄而不是 0,那么如何解决这个问题?请帮我解决它。 我的代码如下:
public int getAge(int year, int month, int day)
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, noofyears;
y = cal.get(Calendar.YEAR);// current year ,
m = cal.get(Calendar.MONTH);// current month
d = cal.get(Calendar.DAY_OF_MONTH);// current day
cal.set(year, month, day);// here ur date
noofyears = (int) (y - cal.get(Calendar.YEAR));
LOGD("Age......", String.valueOf(noofyears));
if ((m < cal.get(Calendar.MONTH)) || ((m == cal.get(Calendar.MONTH)) && (d < cal.get(Calendar.DAY_OF_MONTH))))
--noofyears;
LOGD("Age......", String.valueOf(noofyears));
if (noofyears != 0)
ageCount = noofyears;
else
ageCount = 0;
if (noofyears < 0)
throw new IllegalArgumentException("age < 0");
return noofyears;
【问题讨论】:
可能与***.com/a/20092055/5305430重复 Calculate the age using the date of birth的可能重复 但是我的应用程序在 if (noofyears 应用崩溃时您选择的日期是哪一天? 今天的当前日期 【参考方案1】:这是一个名为 getAge 的 Java 方法,它接受整数表示年月和日,并返回一个 String 类型,该类型包含一个表示年龄的整数。
private String getAge(int year, int month, int day)
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
age--;
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
【讨论】:
今天的日期是 2017 年 7 月 30 日,生日输入是 07/30/1999 - 年龄输出是 17,应该是 18。即使你把 07/29/1999 作为生日输入年龄仍然是17. @OleV.V.关于闰年:考虑出生于 2015 年 3 月 1 日的人,查询 2016 年 2 月 29 日(此处使用德语 dd.mm.yyyy)- 此函数将产生 1 岁,但应该为 0。 现在明白了,@IARI(我很慢)。使用日期是不正确的,因为它不对应闰年和非闰年的相同日期。例如,在闰年 4 月 11 日是第 102 天,在非闰年是 101。所以问题中的代码可能会在生日附近给出不正确的结果。 @Erick 我在你提到的两种情况下都 18 岁。也许您使用过new GregorianCalendar(1999, 7, 29)
或类似的? 7 表示 8 月,而不是预期的 7 月。这是避免使用旧的和过时的Calendar
类的众多原因之一。
不敢相信这是最受好评的答案。它没有考虑闰年。如果任何日期(现在或 DOB)在闰年,则此计算会中断。此外,Calendar 接受从 0 到 11 的月份,即 0 表示 1 月、12 月 11 日等。所以我们需要在调用 dob.set(year,month,day); 时传递months - 1;当然,这需要提及。【参考方案2】:
java.time
为了完整和更新包,这里是使用java.time
(Java 8+)的方式。
Java
public int getAge(int year, int month, int dayOfMonth)
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).getYears();
科特林
fun getAge(year: Int, month: Int, dayOfMonth: Int): Int
return Period.between(
LocalDate.of(year, month, dayOfMonth),
LocalDate.now()
).years
两个 sn-ps 都需要从 java.time
导入以下内容:
import java.time.LocalDate;
import java.time.Period
不建议再使用java.util.Date
和java.util.Calendar
,除非您必须涉及大量遗留代码。
另见Oracle Tutorial。
对于支持 Java 6 或 7 的项目,此功能可通过 ThreeTenBP 获得, 虽然有特殊版本,ThreeTenABP 用于 android 中低于 26 的 API 级别。
更新
现在在 Android 中有API Desugaring,它使java.time
的(一个子集)直接可用(不再需要向后移植库)到低于 26 的 API 级别(不是真正降到版本 1,但可以用于大多数 API 级别现在应该支持)。
【讨论】:
调用需要 API 26。 @RohaitasTanoli 当然,您是否阅读了整个答案,尤其是最后两段?【参考方案3】:private int getAge(String dobString)
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try
date = sdf.parse(dobString);
catch (ParseException e)
e.printStackTrace();
if(date == null) return 0;
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.setTime(date);
int year = dob.get(Calendar.YEAR);
int month = dob.get(Calendar.MONTH);
int day = dob.get(Calendar.DAY_OF_MONTH);
dob.set(year, month+1, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
age--;
return age;
【讨论】:
完美解决方案,成功!!谢谢【参考方案4】:这是 Date
类的 Kotlin 扩展,返回与 Date
对象对应的年龄
val Date.age: Int
get()
val calendar = Calendar.getInstance()
calendar.time = Date(time - Date().time)
return 1970 - (calendar.get(Calendar.YEAR) + 1)
它兼容所有 Android 版本。如果您想知道“1970”是什么,那就是 Unix 纪元。 1970 年 1 月 1 日的时间戳为 0。
【讨论】:
不,它没有。你测试过吗? 这个 Kotlin 版本运行良好,正如它所说的适用于所有版本的 android,这里的许多解决方案都使用需要 8.0 的 LocalDate【参考方案5】: private boolean getAge(int year, int month, int day)
try
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int monthToday = today.get(Calendar.MONTH) + 1;
int monthDOB = dob.get(Calendar.MONTH)+1;
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (age > 18)
return true;
else if (age == 18)
if (monthDOB > monthToday)
return true;
else if (monthDOB == monthToday)
int todayDate = today.get(Calendar.DAY_OF_MONTH);
int dobDate = dob.get(Calendar.DAY_OF_MONTH);
if (dobDate <= todayDate) // should be less then
return true;
else
return false;
else
return false;
else
return false;
catch (Exception e)
e.printStackTrace();
return false;
【讨论】:
【参考方案6】:现在介绍 kotlin 语言:
import java.util.Calendar
fun main(args: Array<String>)
print(getAge(yyyy,mm,dd))
fun getAge(year: Int, month: Int, day: Int): String
val dob = Calendar.getInstance()
val today = Calendar.getInstance()
dob.set(year, month, day)
var age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR)
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
age--
val ageInt = age + 1
return ageInt.toString()
【讨论】:
仅供参考,这些糟糕的日期时间类已被 JSR 310 中定义的 java.time 类所取代。请参阅Answer by deHaar 中的现代解决方案。【参考方案7】:public static int getPerfectAgeInYears(int year, int month, int date)
Calendar dobCalendar = Calendar.getInstance();
dobCalendar.set(Calendar.YEAR, year);
dobCalendar.set(Calendar.MONTH, month);
dobCalendar.set(Calendar.DATE, date);
int ageInteger = 0;
Calendar today = Calendar.getInstance();
ageInteger = today.get(Calendar.YEAR) - dobCalendar.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) == dobCalendar.get(Calendar.MONTH))
if (today.get(Calendar.DAY_OF_MONTH) < dobCalendar.get(Calendar.DAY_OF_MONTH))
ageInteger = ageInteger - 1;
else if (today.get(Calendar.MONTH) < dobCalendar.get(Calendar.MONTH))
ageInteger = ageInteger - 1;
return ageInteger;
考虑今天的日期 - 30th August 2020
如果出生日期 - 29th July 1993
,则输出 - 27
如果出生日期 - 29th August 1993
,则输出 - 27
如果出生日期 - 30th August 1993
,则输出 - 27
如果出生日期 - 31st August 1993
,则输出 - 26
如果出生日期 - 31st September 1993
,则输出 - 26
【讨论】:
【参考方案8】: private void calculateAge()
age.calcualteYear();
age.calcualteMonth();
age.calcualteDay();
age.calculateMonths();
age.calTotalWeeks();
age.calTotalHours();
age.calTotalMins();
age.calTotalSecs();
age.calTotalMilsecs();
// Toast.makeText(getContext(), "click the resulted button"+age.getResult() , Toast.LENGTH_SHORT).show();
result.setText("AGE (DD/MM/YY) :" + age.getResult());
然后创建一个类
public class AgeCalculation
private int startYear;
private int startMonth;
private int startDay;
private int endYear;
private int endMonth;
private int endDay;
private int resYear;
private int resMonth;
private int resDay;
private Calendar start;
private Calendar end;
public String getCurrentDate()
end=Calendar.getInstance();
endYear=end.get(Calendar.YEAR);
endMonth=end.get(Calendar.MONTH);
endMonth++;
endDay=end.get(Calendar.DAY_OF_MONTH);
return endDay+":"+endMonth+":"+endYear;
public void setDateOfBirth(int sYear, int sMonth, int sDay)
startYear=sYear;
startMonth=sMonth;
startDay=sDay;
public void calcualteYear()
resYear=endYear-startYear/(365);
public void calcualteMonth()
if(endMonth>=startMonth)
resMonth= endMonth-startMonth;
else
resMonth=endMonth-startMonth;
resMonth=12+resMonth;
resYear--;
public void calcualteDay()
if(endDay>=startDay)
resDay= endDay-startDay;
else
resDay=endDay-startDay;
resDay=30+resDay;
if(resMonth==0)
resMonth=11;
resYear--;
else
resMonth--;
public String getResult()
return resDay+":"+resMonth+":"+resYear;
【讨论】:
【参考方案9】:public String getAge(int year, int month, int day)
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month-1, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
age--;
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
【讨论】:
月份从0到11【参考方案10】:static int calculateAge(int birthdayDay, int birthdayMonth, int birthdayYear)
DateTime date = DateTime(birthdayYear, birthdayMonth, birthdayDay).toLocal();
DateTime now = DateTime.now().toLocal();
return now.difference(date).inDays ~/ 365.2425;
【讨论】:
【参考方案11】:public int getAge(int year, int month, int day)
final Calendar birthDay = Calendar.getInstance();
birthDay.set(year, month, day);
final Calendar current = Calendar.getInstance();
if (current.getTimeInMillis() < birthDay.getTimeInMillis())
throw new IllegalArgumentException("age < 0");
int age = current.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
if (birthDay.get(Calendar.MONTH) > current.get(Calendar.MONTH) ||
(birthDay.get(Calendar.MONTH) == current.get(Calendar.MONTH) &&
birthDay.get(Calendar.DATE) > current.get(Calendar.DATE)))
age--;
return age;
【讨论】:
无法正常工作【参考方案12】:这是我在源代码中实现的方式,我测试过。希望有用:
public static int getAge(String dateTime, String currentFormat)
SimpleDateFormat dateFormat = new SimpleDateFormat(currentFormat);
try
Date date = dateFormat.parse(dateTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
Date currentDate = new Date();
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentDate);
int currentYear = currentCalendar.get(Calendar.YEAR);
int currentMonth = currentCalendar.get(Calendar.MONTH);
int currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH);
int deltaYear = currentYear - year;
int deltaMonth = currentMonth - month;
int deltaDay = currentDay - day;
if (deltaYear > 0)
if (deltaMonth < 0)
deltaYear --;
else if (deltaDay < 0)
deltaYear --;
return deltaYear;
catch (java.text.ParseException e)
e.printStackTrace();
return 0;
【讨论】:
【参考方案13】:String getAgeInOther(int year, int month, int day)
Calendar today = Calendar.getInstance();
Calendar birth = Calendar.getInstance();
birth.set(year, month, day);
Calendar temp = Calendar.getInstance();
temp.set(year, month, day);
int totalDays = 0;
int intMonth=0,intDays=0;
for (int iYear = birth.get(Calendar.YEAR); iYear <= today.get(Calendar.YEAR); iYear++)
if (iYear == today.get(Calendar.YEAR) && iYear == birth.get(Calendar.YEAR))
for (int iMonth = birth.get(Calendar.MONTH); iMonth <= today.get(Calendar.MONTH); iMonth++)
temp.set(iYear, iMonth, 1);
if ((iMonth == today.get(Calendar.MONTH)) && (iMonth == birth.get(Calendar.MONTH)))
totalDays += today.get(Calendar.DAY_OF_MONTH) - birth.get(Calendar.DAY_OF_MONTH);
else if ((iMonth != today.get(Calendar.MONTH)) && (iMonth != birth.get(Calendar.MONTH)))
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
intMonth++;
else if ((iMonth == birth.get(Calendar.MONTH)))
totalDays +=( birth.getActualMaximum(Calendar.DAY_OF_MONTH)- birth.get(Calendar.DAY_OF_MONTH));
else if ((iMonth == today.get(Calendar.MONTH)))
totalDays += today.get(Calendar.DAY_OF_MONTH);
if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
intMonth++;
intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
else
temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
else if ((iYear != today.get(Calendar.YEAR)) && (iYear != birth.get(Calendar.YEAR)))
for (int iMonth = 0; iMonth < 12; iMonth++)
temp.set(iYear, iMonth, 1);
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
intMonth++;
else if (((iYear) == birth.get(Calendar.YEAR)))
for (int iMonth = birth.get(Calendar.MONTH); iMonth < 12; iMonth++)
temp.set(iYear, iMonth, 1);
if ((iMonth == birth.get(Calendar.MONTH)))
totalDays += (birth.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH));
else
intMonth++;
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
else if (iYear == today.get(Calendar.YEAR))
for (int iMonth = 0; iMonth <= today.get(Calendar.MONTH); iMonth++)
temp.set(iYear, iMonth, 1);
if ((iMonth == today.get(Calendar.MONTH)))
totalDays += today.get(Calendar.DAY_OF_MONTH);
if (birth.get(Calendar.DAY_OF_MONTH)<today.get(Calendar.DAY_OF_MONTH))
intMonth++;
intDays=today.get(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH);
else
temp.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH)-1,1);
intDays=temp.getActualMaximum(Calendar.DAY_OF_MONTH)-birth.get(Calendar.DAY_OF_MONTH)+today.get(Calendar.DAY_OF_MONTH);
else
intMonth++;
totalDays += temp.getActualMaximum(Calendar.DAY_OF_MONTH);
int ageYear=intMonth/12;
int ageMonth=intMonth%12;
int ageDays=intDays;
//TODO if you want age in YEAR:MONTH:DAY REMOVE COMMENTS
//TODO return ageYear+":"+ageMonth+":"+ageDays;
return ""+totalDays;//todo TOTAL AGE IN DAYS
【讨论】:
【参考方案14】:public static String calculateAge(String strDate)
int years = 0;
int months = 0;
int days = 0;
try
long timeInMillis = Long.parseLong(strDate);
Date birthDate = new Date(timeInMillis);
//create calendar object for birth day
Calendar birthDay = Calendar.getInstance();
birthDay.setTimeInMillis(birthDate.getTime());
//create calendar object for current day
long currentTime = System.currentTimeMillis();
Calendar now = Calendar.getInstance();
now.setTimeInMillis(currentTime);
//Get difference between years
years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
int currMonth = now.get(Calendar.MONTH) + 1;
int birthMonth = birthDay.get(Calendar.MONTH) + 1;
//Get difference between months
months = currMonth - birthMonth;
//if month difference is in negative then reduce years by one and calculate the number of months.
if (months < 0)
years--;
months = 12 - birthMonth + currMonth;
if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
months--;
else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
years--;
months = 11;
//Calculate the days
if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
int today = now.get(Calendar.DAY_OF_MONTH);
now.add(Calendar.MONTH, -1);
days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
else
days = 0;
if (months == 12)
years++;
months = 0;
//adarsh
if (currMonth > birthMonth)
if (birthDay.get(Calendar.DATE) > now.get(Calendar.DATE))
months = months - 1;
//---------------------------------
catch (Exception e)
e.printStackTrace();
//Create new Age object
return years + " Y " + months + " M " + days + " days";
【讨论】:
【参考方案15】:这是我在 Kotlin 中的解决方案:
import java.time.LocalDateTime
fun getAge(birthYear: Int, birthMonth: Int, birthDay: Int): Int
var age: Int = LocalDateTime.now().year - birthYear
if (birthMonth > LocalDateTime.now().monthValue || birthMonth == LocalDateTime.now().monthValue && birthDay > LocalDateTime.now().dayOfMonth) age--
if (age < 0) age = 0
return age
【讨论】:
【参考方案16】:int age =0;
age = yearLatest - yearBirth;
if (monthAge > currentMonth)
if (age != 0)
age = age - 1;
else if(monthAge == currentMonth)
if (dayAge > currentDay)
if (age != 0)
age = age - 1;
return age;
【讨论】:
【参考方案17】:如果我们想直接检查年龄是否低于或高于 X 年龄,那么我们可以使用 LocalDate 类型,适用于所有 Android API 级别。
LocalDate.now().minusYears(18).isBefore(value) //value is your localDate
【讨论】:
【参考方案18】:这是我能做到的最短时间。
static int calculateAge(Calendar birthDay)
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
if (birthDay.get(Calendar.DAY_OF_YEAR) < today.get(Calendar.DAY_OF_YEAR))
age--;
return age;
【讨论】:
【参考方案19】:使用 DateTime 的新语言 Dart
static int getPerfectAgeInYears(DateTime dob,DateTime today)
dob = DateTime(dob.year,dob.month,dob.day);
int ageInteger = 0;
today = DateTime(today.year,today.month,today.day);
ageInteger = today.year-dob.year;
if (today.month == dob.month)
if (today.day < dob.day)
ageInteger = ageInteger - 1;
else if (today.month < dob.month)
ageInteger = ageInteger - 1;
return ageInteger;
调用 print(getPerfectAgeInYears(DateTime(2000,6,4),DateTime.now())); 考虑今天的日期 - 2020 年 8 月 30 日
如果出生日期 - 1993 年 7 月 29 日,则输出 - 27
如果出生日期 - 1993 年 8 月 29 日,则输出 - 27
如果出生日期 - 1993 年 8 月 30 日,则输出 - 27
如果出生日期 - 1993 年 8 月 31 日,则输出 - 26
如果出生日期 - 1993 年 9 月 31 日,则输出 - 26
【讨论】:
问题似乎不在Dart
当我在 Dart 中需要这样的代码时,我结束了这个问题。所以我发布了代码。以上是关于从 BirthDate 计算年龄的主要内容,如果未能解决你的问题,请参考以下文章