java.time and ThreeTenABP
Sorry, I can write this in Java only. Please translate yourself. Your task is best solved using java.time, the modern Java date and time API.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
LocalDate date = LocalDate.now(ZoneId.of("Europe/London")).plusMonths(14);
String result = date.format(dateFormatter);
System.out.println("Result: " + result);
Output when running today:
Result: 22-12-2020
Fixing your code
If you insist on using the notoriously troublesome and long outdated SimpleDateFormat
class, just remove .format(this)
from your code. I bet the exception is coming from there, and it’s wrong since you have an almost correct call to the format
method in the following line.
private fun bestBeforeDate(cal: Calendar = Calendar.getInstance()): String
{
cal.add(Calendar.MONTH, 14)
val format1 = SimpleDateFormat("dd-MM-yyyy")
return getString(R.string.best_before_date) + format1.format(cal.time)
}
The format
method expects either a Date
(another poorly designed and long outdated class) or a Long
. Since this
was neither of those, you got the exception.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both 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 non-Android 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