Reputation: 23
I am working on a project in my CIS 163 class that is effectively a campsite reservation system. The bulk of the code was provided and I just have to add certain functionalities to it. Currently I need to be able to determine how much time has passed between 2 different GregorianCalendar instances (one being the current date, the other being a predetermined "check out") represented by days. I haven't been able to figure out quite how to do this, and was hoping someone here might be able to help me out.
Upvotes: 0
Views: 403
Reputation: 86282
Since you have been forced to use the old and poorly designed GregorianCalendar
class, the first thing you should do is convert each of the two GregorianCalendar
objects to a modern type. Since Java 8 GregorianCalendar
has a method that converts it to ZonedDateTime
. Check the documentation, I include a link below.
Now that you’ve got two ZonedDateTime
objects, there are different paths depending on your exact requirements. Often one will use Duration.between()
for finding the duration, the amount of time between them in hours, minutes, seconds and fraction of second. If you know that you will always need just one of those time units, you may instead use for example ChronoUnit.HOURS.between()
or ChronoUnit.MILLISECONDS.between()
. If you need to count days, use ChronoUnit.DAYS.between()
.
If instead you need the time in months and days, you should instead use Period.between()
.
GregorianCalendar
(long outdated, don’t use unless forced to)Duration
ChronoUnit
Period
ZonedDateTIme
, Duration
, ChronoUnit
and Period
belong.Upvotes: 0
Reputation: 98
The GregorianCalendar is old and you shouldn't really use it anymore. It was cumbersome and was replaced by the "new" java.time module since Java 8.
Still, if you need to compare using GC instances, you could easily calculate time using milliseconds between dates, like this:
GregorianCalendar date1 = new GregorianCalendar();
GregorianCalendar date2 = new GregorianCalendar();
// Adding 15 days after the first date
date2.add(GregorianCalendar.DAY_OF_MONTH, 15);
long duration = (date2.getTimeInMillis() - date1.getTimeInMillis() )
/ ( 1000 * 60 * 60 * 24) ;
System.out.println(duration);
If you want to use the new Time API, the following code would work.
LocalDate date1 = LocalDate.now();
LocalDate date2 = date1.plusDays(15);
Period period = Period.between(date1, date2);
int diff = period.getDays();
System.out.println(diff);
If you need to convert between the types (e.g. you're working with legacy code), you can do it like this:
LocalDate date3 = gcDate1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate date4 = gcDate2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Also I'm pretty sure this question must've been asked over and over again, so make sure you search properly before asking.
Upvotes: 1