Yunus Haznedar
Yunus Haznedar

Reputation: 1614

Can't get year between two dates

I want to get year difference between two dates. One of these dates is the current date and time. And the other one is user's birth date.

I can get user's birth date properly, like that: 1995-06-18T19:36:00.000Z

I'm getting this error:

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

Here is my function:

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;
}

Upvotes: 1

Views: 2120

Answers (4)

P R
P R

Reputation: 105

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;
}

Upvotes: 0

user7605325
user7605325

Reputation:

First of all, you don't need to do this:

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

Just do:

Date date1 = cal.getTime();

And to calculate the age, put date1 before date2, otherwise you'll have a negative value:

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

Using comingDate as 1995-06-18T19:36:00.000Z, I've got the result 8050 (which is equivalent to 22 years), so it seems to be correct.

If you want the age in years instead of days:

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

The result will be 22.


New Java Date/Time API

If you're ok about adding a dependency to your Android project, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes, together with the ThreeTenABP (more on how to use it here).

All the classes are in the org.threeten.bp package. The code is much simpler:

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

To get the age in years I had to use a ZonedDateTime, because some units don't work with Instant.

Upvotes: 2

from56
from56

Reputation: 4127

Very simple :

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

Date.getTime() gets time in milliseconds since "Jan 1 1970" then we need to divide by the milliseconds in a day.

EDITED And you don't need a Calendar to get actual time, new Date().getTime(); returns it

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

If your app uses so many date or times don't save it as Strings, save it as longs, much simpler.

Upvotes: 1

ramandeep singh
ramandeep singh

Reputation: 51

this will help you

 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");
}

Upvotes: 0

Related Questions