无法在两个日期之间获取年份

Can't get year between two dates

我想得到两个日期之间的年份差异。这些日期之一是当前日期和时间。另一个是用户的出生日期。

我可以正确获取用户的出生日期,像这样:1995-06-18T19:36:00.000Z

我收到此错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference

这是我的函数:

public int calculateAge(String comingDate)
{
    long userAge = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+03:00"));
    Calendar cal = Calendar.getInstance();
    try
    {
        Date date1 = sdf.parse(sdf.format(cal.getTime()));
        Date date2 = sdf.parse(comingDate);
        userAge = (date2.getTime() - date1.getTime())/86400000;

    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }

    return (int)userAge;
}

这对你有帮助

 public String get_count_of_days(String Created_date_String, String 
    Expire_date_String) 

 {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", 
Locale.getDefault());

Date Created_convertedDate = null, Expire_CovertedDate = null, todayWithZeroTime = null;
try {
    Created_convertedDate = dateFormat.parse(Created_date_String);
    Expire_CovertedDate = dateFormat.parse(Expire_date_String);

    Date today = new Date();

    todayWithZeroTime = dateFormat.parse(dateFormat.format(today));
} catch (ParseException e) {
    e.printStackTrace();
}

int c_year = 0, c_month = 0, c_day = 0;

if (Created_convertedDate.after(todayWithZeroTime)) {
    Calendar c_cal = Calendar.getInstance();
    c_cal.setTime(Created_convertedDate);
    c_year = c_cal.get(Calendar.YEAR);
    c_month = c_cal.get(Calendar.MONTH);
    c_day = c_cal.get(Calendar.DAY_OF_MONTH);

} else {
    Calendar c_cal = Calendar.getInstance();
    c_cal.setTime(todayWithZeroTime);
    c_year = c_cal.get(Calendar.YEAR);
    c_month = c_cal.get(Calendar.MONTH);
    c_day = c_cal.get(Calendar.DAY_OF_MONTH);
}


/*Calendar today_cal = Calendar.getInstance();
int today_year = today_cal.get(Calendar.YEAR);
int today = today_cal.get(Calendar.MONTH);
int today_day = today_cal.get(Calendar.DAY_OF_MONTH);
*/

Calendar e_cal = Calendar.getInstance();
e_cal.setTime(Expire_CovertedDate);

int e_year = e_cal.get(Calendar.YEAR);
int e_month = e_cal.get(Calendar.MONTH);
int e_day = e_cal.get(Calendar.DAY_OF_MONTH);

Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();

date1.clear();
date1.set(c_year, c_month, c_day);
date2.clear();
date2.set(e_year, e_month, e_day);

long diff = date2.getTimeInMillis() - date1.getTimeInMillis();

float dayCount = (float) diff / (24 * 60 * 60 * 1000);

return ("" + (int) dayCount + " Days");
}

很简单:

  int daysDifference = (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000);

Date.getTime() 获取自 "Jan 1 1970" 以来的毫秒数,然后我们需要除以一天中的毫秒数。

已编辑 而且您不需要日历来获取实际时间, new Date().getTime(); returns它

    int daysPassedSinceADate =  (new Date().getTime() - date.getTime()) / (24 * 60 * 60 * 1000);

如果您的应用使用了很多日期或时间,请不要将其保存为字符串,将其保存为长整数,这样会简单得多。

首先,你不需要这样做:

Date date1 = sdf.parse(sdf.format(cal.getTime()));

就这样:

Date date1 = cal.getTime();

并且要计算年龄,请将 date1 放在 date2 之前,否则您将得到一个负值:

userAge = (date1.getTime() - date2.getTime()) / 86400000;

使用comingDate作为1995-06-18T19:36:00.000Z,我得到的结果是8050(相当于22年),所以看起来是正确的。

如果您想要而不是天的年龄:

userAge = (date1.getTime() - date2.getTime()) / 86400000 / 365;

结果将是 22


新建JavaDate/TimeAPI

如果您愿意为 Android 项目添加依赖项,则可以使用 ThreeTen Backport, a great backport for Java 8's new date/time classes, together with the ThreeTenABP (more on how to use it ).

所有 类 都在 org.threeten.bp 包中。代码简单多了:

import org.threeten.bp.temporal.ChronoUnit;
import org.threeten.bp.Instant;
import org.threeten.bp.ZonedDateTime;

String comingDate = "1995-06-18T19:36:00.000Z";
// get the number of days between comingDate and current date (result is 8050)
int userAge = (int) ChronoUnit.DAYS.between(Instant.parse(comingDate), Instant.now()); // 8050
// get the age in years (result is 22)
userAge = (int) ChronoUnit.YEARS.between(ZonedDateTime.parse(comingDate), ZonedDateTime.now()); // 22

为了获得以年为单位的年龄,我不得不使用 ZonedDateTime,因为有些单位不适用于 Instant

public long getDifferenceBetweenDates(Date dateOfBirth, Date currentDate) {
    long difference = currentDate.getTime() - dateOfBirth.getTime();
    long daysInMilliseconds = 60 * 60 * 24 * 1000;
    long elapsedDays = difference / daysInMilliseconds;
    return elapsedDays;
}