0

I want to check how many days it has been since my user logged in:

Calendar lastLogin = Calendar.getInstance();
lastLogin.setTime(randomPlayer.getLastLogin());
Calendar today = Calendar.getInstance();

How would I subtract this to get the difference in days between the two? I.e number of days since last login.

Green_qaue
  • 3,561
  • 11
  • 47
  • 89

1 Answers1

1

I suggest using LocalDate instead:

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DaysBetween {

    public static void main(String[] args) {
        LocalDate lastLogin = LocalDate.of(2017, 4, 1);
        LocalDate today = LocalDate.now();
        System.out.println(daysBetween(lastLogin, today));
    }

    private static long daysBetween(LocalDate from, LocalDate to) {
        return ChronoUnit.DAYS.between(from, to);
    }
}

Or, if you really want to stick to Calendar:

import java.time.temporal.ChronoUnit;
import java.util.Calendar;

public class DaysBetween {

    public static void main(String[] args) {
        Calendar lastLogin = Calendar.getInstance();
        lastLogin.set(Calendar.YEAR, 2017);
        lastLogin.set(Calendar.MONTH, 3);
        lastLogin.set(Calendar.DAY_OF_MONTH, 1);
        Calendar today = Calendar.getInstance();
        System.out.println(daysBetween(lastLogin, today));
    }

    private static long daysBetween(Calendar from, Calendar to) {
        return ChronoUnit.DAYS.between(from.toInstant(), to.toInstant());
    }
}
Marvin
  • 13,325
  • 3
  • 51
  • 57