MyoZaw Oo
MyoZaw Oo

Reputation: 127

How can I calculate the remaining days?

private long calculateNextBirthday() {

    final Calendar c = Calendar.getInstance();

    c.set(2015, 8, 20);
      //this is birthdate. set it to date you get from date picker

    final Calendar today = Calendar.getInstance();

    long eta = c.getTimeInMillis();
    long now = System.currentTimeMillis();

    long durationMills = eta - now;

    long diffSeconds = durationMills / 1000;
    long diffMinutes = diffSeconds / 60;
    long diffHours = diffMinutes / 60;
    long diffDays = diffHours / 24;
    long remainDays = diffHours % 24;


    final long millis = c.getTimeInMillis()
            - today.getTimeInMillis();

    // Convert to days
    final long days = millis / 86400000; // Precalculated
    // (24 *
    // 60 *
    // 60 *
    // 1000)

    return diffDays;
}

This method is supposed to calculate the remaining days for a given date, but I don't know why this doesn't return the exact value. I think this should return 30 or 31, but I get 62.

Edit:

I changed my code, but I still don't get the exact value:

private long calculateRemainingDays() {

    final Calendar c = Calendar.getInstance();
    c.set(2015, 7, 23);
    final Calendar today = Calendar.getInstance();

    final long millis = c.getTimeInMillis()
            - today.getTimeInMillis();
    // Convert to days
    final long days = millis / 86400000;
    return days;
}

Upvotes: 2

Views: 5265

Answers (3)

Tom
Tom

Reputation: 17567

There are already two answers which either explains why OP's original code didn't work or how he could use java.util.Date to solve his question.

I'd like to add a Java 8 version with java.time just to show a more "modern" approach with the newer API.

The calculateRemainingDays method can look like this:

private long calculateRemainingDays(final Temporal target) {
    final LocalDate today = LocalDate.now();
    return today.until(target, ChronoUnit.DAYS);
}

It gets a target Temporal and calculates the difference in days from today.

This method can be called like this:

final LocalDate target = LocalDate.of(2015, 8, 23);
System.out.println(calculateRemainingDays(target));

The first line creates a LocalDate for the 23rd of August 2015(*) and passes it to the calculation method. The result will be printed as ("now" is 20th of July 2015):

34

It should be noted that the result will be negative if the target date is before today.


(*) Note, unlike Calendar the months in LocalDate are not zero-based, so 8 means "August" and not "September".

Snippet of the JavaDoc of LocalDate.of(int, int, int):

public static LocalDate of(int year, int month, int dayOfMonth)

Parameters:
    year - the year to represent, from MIN_YEAR to MAX_YEAR
    month - the month-of-year to represent, from 1 (January) to 12 (December)
    dayOfMonth - the day-of-month to represent, from 1 to 31

If someone is unsure on how to use this method and might get confused about this and the Calendar version, then he could use the overloaded version of LocalDate.of (JavaDoc):

final LocalDate target = LocalDate.of(2015, Month.AUGUST, 24);

This takes a value from the Month enum and since it states the name of the month, there can't be a confusion about that.

Upvotes: 1

CallSign-Filter
CallSign-Filter

Reputation: 1301

What you are getting is correct, when you are using 8 for your month you are actually using September, it is indexed at 0. It is better practice to use the built in constants like Calendar.AUGUST, which is 7.

Upvotes: 2

Razib
Razib

Reputation: 11153

Instead of using own code, you code you can use date arithmetic (Date API minus along with DAYS.convert() ) to find the difference. For populating fromDate and toDate I used here SimpleDateFormat. You may populate Date by other means. But the main thing is you need two Date to find the difference.

SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy");
String date1 = "20 05 1985";
String date2 = "22 05 1999";

try {
    Date toDate = dateFormat.parse(date2);
    Date fromDate = dateFormat.parse(date1);
    long diff = toDate.getTime() - fromDate.getTime();
    System.out.println ("Difference in Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

Upvotes: 1

Related Questions