【问题标题】:how to get number of years between two dates in android [duplicate]如何在android中获取两个日期之间的年数[重复]
【发布时间】:2014-11-27 11:19:05
【问题描述】:

您好,我正在创建一个 android 应用程序,其中我有两个不同日期的字符串现在我想获取这些日期之间的年数,请帮助我如何做到这一点?这是我的代码

                    String  birthday=p.getString("BirthDay");

                     Log.i("bd", String.valueOf(birthday));
                     Calendar c = Calendar.getInstance();


                     SimpleDateFormat df = new SimpleDateFormat("dd MMM, yyyy");
                     final String formattedDate = df.format(c.getTime());
                     Log.i("formattedDate", String.valueOf(formattedDate));

生日是保存日期,而格式化日期是当前日期,现在我想要这些之间的区别

【问题讨论】:

  • 将字符串解析为日期,减去它们,然后从结果中获取年份。 Android 中的所有日期/时间都是基于 Unix 纪元的长整数。
  • 您可以使用c.get(Calendar.YEAR)从日历中获取年份。

标签: android datetime android-calendar android-datepicker


【解决方案1】:

请试试这个代码

    String birthday = p.getString("BirthDay");
    Calendar calendarBirthday = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy");
    calendarBirthday.setTime(sdf.parse(birthday));
    Calendar calendarNow = Calendar.getInstance();
    int yearNow = calendarNow.get(Calendar.YEAR);
    int yearBirthday = calendarBirthday.get(Calendar.YEAR);
    int years = yearNow - yearBirthday;

【讨论】:

  • 使用这段代码我得到了这个 java.text.ParseException: Unparseable date: "1 January,2000" (at offset 10)
  • 您需要更改 simpledateformat 中的格式字符串。它可能是这样的:“dd MMMM,yyyy”
  • 我这样做了,但同样的例外:(
【解决方案2】:
int getYear(Date date1,Date date2){ 
  SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy");
  Integer.parseInt(simpleDateformat.format(date1));

  return Integer.parseInt(simpleDateformat.format(date2))- Integer.parseInt(simpleDateformat.format(date1));

}

【讨论】:

  • 请在您的回答中添加一些解释。
【解决方案3】:

传递你的出生日期

public int getAge (int _year, int _month, int _day) {

    GregorianCalendar cal = new GregorianCalendar();
    int y, m, d, a;         

    y = cal.get(Calendar.YEAR);
    m = cal.get(Calendar.MONTH) + 1;
    d = cal.get(Calendar.DAY_OF_MONTH);
    cal.set(_year, _month, _day);
    a = y - cal.get(Calendar.YEAR);
    if ((m < cal.get(Calendar.MONTH))
                    || ((m == cal.get(Calendar.MONTH)) && (d < cal
                                    .get(Calendar.DAY_OF_MONTH)))) {
            --a;
    }
    if(a < 0)
            throw new IllegalArgumentException("Age < 0");
    return a;
}

【讨论】:

  • 如果看起来正确,请投票给我
  • 请告诉我如何从“1990 年 7 月 15 日”获取年份
猜你喜欢
  • 1970-01-01
  • 2012-12-13
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多