Recently, I try to port one of our old code base, from Calendar
to java.time
, as we need quite a number of arithmetic functionalities, which is only found in java.time
.
If we use Calendar
in our current code base, we need to perform a lot of conversion back-and-forth (From Calendar
to Instant
, From Instant
back to Calendar
), in the middle of our code.
To avoid such cumbersome conversion, we decide to eliminate usage of Calendar
, and port them to equivalent java.time
code.
I'm a bit skeptical on my port. As compared with Calendar code, it seems to
- Create more temporary object instances within the while loop.
- Requires more code statements.
Calendar code
// reminderCal is Calendar object.
long startTimestamp = getStartTimestamp();
reminderCal.setTimeInMillis(startTimestamp);
while (startTimestamp <= maxTimestamp) {
resultList.add(startTimestamp);
reminderCal.add(Calendar.DAY_OF_MONTH, 1);
startTimestamp = reminderCal.getTimeInMillis();
}
return resultList;
java.time code
// Epoch timestamp loopTs as initial input.
long startTimestamp = getStartTimestamp();
final ZoneId zoneId = ZoneId.systemDefault();
while (startTimestamp <= maxTimestamp) {
resultList.add(startTimestamp);
// More code, more temporary instances required compared
// with Calendar's version. Not sure we're doing the right
// way.
Instant instant = Instant.ofEpochMilli(startTimestamp);
LocalDateTime time = LocalDateTime.ofInstant(instant, zoneId);
time = time.plus(1, ChronoUnit.DAYS);
startTimestamp = time.atZone(zoneId).toInstant().toEpochMilli();
}
return resultList;
For the above code, I was wondering, are we doing the port correctly and optimized? Is there any room we can improve in our java.time
's port?