Java Calendar: Subtract two Dates to get difference in days between the two -
this question has answer here:
i want check how many days has been since user logged in:
calendar lastlogin = calendar.getinstance(); lastlogin.settime(randomplayer.getlastlogin()); calendar today = calendar.getinstance();
how subtract difference in days between two? i.e number of days since last login.
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 really want stick 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()); } }
Comments
Post a Comment