java.time
LocalDate date = LocalDate.of(2019, Month.DECEMBER, 25);
switch (recurrence) {
case "Bi-Weekly": {
date = date.plusWeeks(2);
break;
}
case "Month": {
date = date.plusMonths(1);
break;
}
case "Quarterly": {
date = date.plusMonths(3);
break;
}
case "Half Yearly": {
date = date.plusMonths(6);
break;
}
case "Year": {
date = date.plusYears(1);
break;
}
default:
System.err.println("Unrecognized recurrence: " + recurrence);
break;
}
System.out.println("Added for " + recurrence + " gave: " + date);
Trying the code out with the difference strings (in a different order) gave:
Added for Bi-Weekly gave: 2020-01-08
Added for Year gave: 2020-12-25
Added for Quarterly gave: 2020-03-25
Added for Half Yearly gave: 2020-06-25
Added for Month gave: 2020-01-25
Have your calendar events got time of day too? No problem: the code works the same if using a ZonedDateTime
or a LocalDateTime
instead of a LocalDate
.
The Calendar
class that you used is poorly designed and long outdated. I find java.time, the modern Java date and time API, so much nicer to work with. Which is why I wanted to show you this option.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links