java - 如何计算年龄或java中两个日期之间的差异

标签 java date date-difference

我想得到两个日期之间的月数。日期是某人的生日和当前日期。所以我得到的是两个日期之间的年数,而不是月数..

假设我的日期是 06/09/201106/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;

最佳答案

我最近创建了一个演示并上传了 here .

它正在使用 JodaTime高效结果的库。

希望有用。

截图:

screenshot

代码:

主 Activity .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

<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" />

注意:

1) 不要忘记添加 JodaTime 库到你的项目

2) 正如您在布局文件中看到的那样,我使用固定值 "Start Date","End Date"来计算日期差异 和固定值 "Birth Date"来计算年龄。您可以用您的动态值替换它

关于java - 如何计算年龄或java中两个日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20421841/

相关文章:

java - ThreadLocal 类的目的和用途?

java - GWT 中条件属性的 GSS CSS 表达式?

PHP计算时间差,结果错误1小时

android - 如何计算用户通过android studio中的datepicker输入的两个日期之间的天数

java - 以 Short 基元类型获取 Java 8 中两个日期之差(天数)的最简单方法

java - 排除参数化测试类中的非参数测试

Java线程notify()方法

MySQL - 选择日期 < X

swift - 从 UTC 转换为本地时区会给出错误的结果

java - 如何检查日期和时间戳是在 20 分钟之前