如何在java中计算两个日期之间的年龄或差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20421841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to calculate age or difference between two dates in java
提问by XylemRaj
I want to get the number of months between 2 dates.The dates are someones birthday and the current date.So i m getting the number of years in between the two dates but not the number of months..
我想得到两个日期之间的月数。日期是某人的生日和当前日期。所以我得到了两个日期之间的年数,而不是月数。
Suppose my dates are 06/09/2011and 06/11/2012.So i want the answer to be 1yr 2mths .I am getting the year but not the month.Please help.Below is the code for getting the number of years
假设我的日期是06/09/2011和06/11/2012。所以我希望答案是 1yr 2mths 。我得到的是年份而不是月份。请帮忙。下面是获取年数的代码
public int getAge(Date dateOfBirth) {
today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
birthDate.setTime(dateOfBirth);
if (birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
month = today.get(Calendar.MONTH) - birthDate.get(Calendar.MONTH);
if ( (birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3) ||
(birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH ))){
days = birthDate.get(Calendar.DAY_OF_MONTH) - today.get(Calendar.DAY_OF_MONTH);
age--;
Toast.makeText(getApplicationContext(), "inside if", Toast.LENGTH_SHORT).show();
Log.e("month is",month+"");
Log.e("Days",days+ " left");
}else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH )) &&
(birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH ))){
Toast.makeText(getApplicationContext(), "inside else if", Toast.LENGTH_SHORT).show();
age--;
}
return age;
采纳答案by Mehul Joisar
I have recently created a demo and uploaded here.
我最近创建了一个演示并上传到这里。
It is using JodaTime
library for efficient results.
它正在使用JodaTime
库来获得有效的结果。
I hope it will be useful.
我希望它会很有用。
Screenshot:
截屏:
Code:
代码:
MainActivity.java
主活动.java
public class MainActivity extends Activity {
private SimpleDateFormat mSimpleDateFormat;
private PeriodFormatter mPeriodFormat;
private Date startDate;
private Date endDate;
private Date birthDate;
private TextView tvStartDate,tvEndDate,tvDifferenceStandard,tvDifferenceCustom,tvBirthDate,tvAgeStandard,tvAgeCustom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//determine dateDiff
Period dateDiff = calcDiff(startDate,endDate);
tvDifferenceStandard.setText(PeriodFormat.wordBased().print(dateDiff));
tvDifferenceCustom.setText( mPeriodFormat.print(dateDiff));
//determine age
Period age = calcDiff(birthDate,new Date());
tvAgeStandard.setText(PeriodFormat.wordBased().print(age));
tvAgeCustom.setText( mPeriodFormat.print(age));
}
private void init() {
//ui
tvStartDate = (TextView)findViewById(R.id.tvStartDate);
tvEndDate = (TextView)findViewById(R.id.tvEndDate);
tvDifferenceStandard = (TextView)findViewById(R.id.tvDifferenceStandard);
tvDifferenceCustom = (TextView)findViewById(R.id.tvDifferenceCustom);
tvBirthDate = (TextView)findViewById(R.id.tvBirthDate);
tvAgeStandard = (TextView)findViewById(R.id.tvAgeStandard);
tvAgeCustom = (TextView)findViewById(R.id.tvAgeCustom);
//components
mSimpleDateFormat = new SimpleDateFormat("dd/MM/yy");
mPeriodFormat = new PeriodFormatterBuilder().appendYears().appendSuffix(" year(s) ").appendMonths().appendSuffix(" month(s) ").appendDays().appendSuffix(" day(s) ").printZeroNever().toFormatter();
try {
startDate = mSimpleDateFormat.parse(tvStartDate.getText().toString());
endDate = mSimpleDateFormat.parse(tvEndDate.getText().toString());
birthDate = mSimpleDateFormat.parse(tvBirthDate.getText().toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Period calcDiff(Date startDate,Date endDate)
{
DateTime START_DT = (startDate==null)?null:new DateTime(startDate);
DateTime END_DT = (endDate==null)?null:new DateTime(endDate);
Period period = new Period(START_DT, END_DT);
return period;
}
}
activity_main.xml
活动_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date Diff Calculator"
android:textStyle="bold"
android:gravity="center"
android:background="@android:color/darker_gray"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Start Date:" />
<TextView
android:id="@+id/tvStartDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="06/09/2011" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="End Date:" />
<TextView
android:id="@+id/tvEndDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="29/10/2013" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Difference (Standard)" />
<TextView
android:id="@+id/tvDifferenceStandard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="result" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Difference (Custom)" />
<TextView
android:id="@+id/tvDifferenceCustom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="result" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Age Calculator"
android:textStyle="bold"
android:gravity="center"
android:background="@android:color/darker_gray"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Birth Date:" />
<TextView
android:id="@+id/tvBirthDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="01/09/1989" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Age (Standard)" />
<TextView
android:id="@+id/tvAgeStandard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="result" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="Age (Custom)" />
<TextView
android:id="@+id/tvAgeCustom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="result" />
Note:
笔记:
1)
don't forget to add JodaTime library
to your project
1)不要忘记add JodaTime library
你的项目
2)
As you can see in layout file, I have used fixed value for "Start Date","End Date" to calculate Date Difference
and fixed value for "Birth Date" to calculate Age
. You may replace it with your dynamic values
.
2) 正如您在布局文件中看到的,我使用了固定值 for"Start Date","End Date" to calculate Date Difference
和固定值"Birth Date" to calculate Age
. 你可以replace it with your dynamic values
。
回答by GrIsHu
Joda Timehas code to do all this and more
Joda Time有代码可以完成所有这些以及更多
You can do the following to get the month between two dates:
您可以执行以下操作来获取两个日期之间的月份:
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
Check out Link
查看链接
Note:that if your dates are 2013-01-31
and 2013-02-01
, you get a distance of 1 month this way, which may or may not be what you want.
注意:如果您的日期是2013-01-31
和2013-02-01
,那么您将获得 1 个月的距离,这可能是您想要的,也可能不是。
回答by griFlo
java.time
时间
Because this answer got referenced from here…
因为这个答案是从这里引用的......
With java.timeclasses you can calculate the age very easy:
使用java.time类,您可以非常轻松地计算年龄:
long years = ChronoUnit.YEARS.between(LocalDate.of(1900, Month.NOVEMBER, 20), LocalDate.now());
or (if you need year and months)
或(如果您需要年份和月份)
Period p = Period.between(birthday, today);
p.getYears();
p.getMonths();
To count all the months in the entire period, as asked in the Question, call toTotalMonths
.
要按问题中的要求计算整个期间的所有月份,请致电toTotalMonths
。
int totalMonths = p.toTotalMonths();
回答by UJJVAL KUMAR
Age can be calculate in a very easy way. The following is my complete java code .
年龄可以很容易地计算出来。以下是我完整的java代码。
public class age {
public static void main(String [] args){
Scanner s=new Scanner(System.in);
Date dd=new Date();
int d=Integer.parseInt(new SimpleDateFormat("dd").format(dd));
int m=Integer.parseInt(new SimpleDateFormat("MM").format(dd));
int y=Integer.parseInt(new SimpleDateFormat("yyyy").format(dd));
System.out.println( "Enter Day ");
int d1=Integer.parseInt(s.nextLine());
System.out.println( "Enter Month ");
int m1=Integer.parseInt(s.nextLine());
System.out.println( "Year");
int y1=Integer.parseInt(s.nextLine());
if(d<d1){
d+=30;
m-=1;
}
if(m<m1){
m+=12;
y-=1;
}
System.out.println((y-y1)+" years "+(m-m1)+" month "+(d-d1)+" days ");
}
}