1

I want to return the value of the calendar + 14 months using the SimpleDateFormat but am getting the below error.

private fun bestBeforeDate(cal: Calendar = Calendar.getInstance()): String
    {
        cal.add(Calendar.MONTH, 14)
        val format1 = SimpleDateFormat("dd-MM-yyy", Locale.getDefault()).format(this)
        return getString(R.string.best_before_date) + format1.format(cal)
    }
java.lang.IllegalArgumentException: Cannot format given Object as a Date
Brummerly
  • 90
  • 1
  • 11
  • you can try with `add(Calender.YEAR,1) and add(Calender.MONTH,2). may be it works – Noshaf Oct 22 '19 at 13:12
  • 1
    Then you should set Calendar year as +1 and month as +2, I can guide you better if you provide your expected String – Koushik Mondal Oct 22 '19 at 13:12
  • 1
    Why are you passing this to the format method? That is what is causing the error. – jalynn2 Oct 22 '19 at 13:13
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Oct 22 '19 at 13:19
  • I am clearly overthinking this and confused myself. I just want the output string to be the return of the current date + 14 months. – Brummerly Oct 22 '19 at 13:19

2 Answers2

1

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0
    import java.util.Calendar;
import java.util.TimeZone;

/**
 * Java program to add, subtract dates, month and year using Calendar in Java.
 * Apart from date, Calendar class also provide time related information and can
 * be used to add and subtract hours, minutes and seconds from time in Java.
 *
 * @author Shahzad Ali
 */
public class DateAndTimeArithmetic {

    public static void main(String args[]){

        //Java calendar in default timezone and default locale
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("GMT"));

        System.out.println("current date: " + getDate(cal));


        //adding days into Date in Java
        cal.add(Calendar.DATE, 2);
        System.out.println("date after 2 days : " + getDate(cal));

        //subtracting days from Date in Java
        cal.add(Calendar.DATE, -2);
        System.out.println("date before 2 days : " + getDate(cal));


       //adding moths into Date
        cal.add(Calendar.MONTH, 5);
        System.out.println("date after 5 months : " + getDate(cal));

        //subtracting months from Date
        cal.add(Calendar.MONTH, -5);
        System.out.println("date before 5 months : " + getDate(cal));

        //adding year into Date
        cal.add(Calendar.YEAR, 5);
        System.out.println("date after 5 years : " + getDate(cal));

        //subtracting year from Date
        cal.add(Calendar.YEAR, -5);
        System.out.println("date before 5 years : " + getDate(cal));

        //date after 200 days from now, takes care of how many days are in month
        //for years calendar takes care of leap year as well
        cal.add(Calendar.DATE, 200);
        System.out.println("date after 200 days from today : " + getDate(cal));

        System.out.println("current time in GMT: " + getTime(cal));

        //adding hours into Date
        cal.add(Calendar.HOUR_OF_DAY, 3);
        System.out.println("Time after 3 hours : " + getTime(cal));

        //subtracting hours from Date time
        cal.add(Calendar.HOUR_OF_DAY, -3);
        System.out.println("Time before 3 hours : " + getTime(cal));

        //adding minutes into Date time
        cal.add(Calendar.MINUTE, 3);
        System.out.println("Time after 3 minutes : " + getTime(cal));

        //subtracting minutes from Date time
        cal.add(Calendar.HOUR_OF_DAY, -3);
        System.out.println("Time before 3 minuets : " + getTime(cal));

    }

    /**
     *
     * @return current Date from Calendar in dd/MM/yyyy format
     * adding 1 into month because Calendar month starts from zero
     */
    public static String getDate(Calendar cal){
        return "" + cal.get(Calendar.DATE) +"/" +
                (cal.get(Calendar.MONTH)+1) + "/" + cal.get(Calendar.YEAR);
    }

    /**
     *
     * @return current Date from Calendar in HH:mm:SS format
     *
     * adding 1 into month because Calendar month starts from zero
     */
    public static String getTime(Calendar cal){
        return "" + cal.get(Calendar.HOUR_OF_DAY) +":" +
                (cal.get(Calendar.MINUTE)) + ":" + cal.get(Calendar.SECOND);
    }

}

Sample Output Should be like this: current date: 22/10/2019 date after 2 days : 22/10/2019 date before 2 days : 24/10/2019 date after 5 months : 22/3/2020

etc...

  • 1
    These terrible date-time classes were supplanted years ago by the *java.time* classes defined in JSR 310. See the modern solution in the [Answer by Ole V.V.](https://stackoverflow.com/a/58505299/642706) – Basil Bourque Oct 22 '19 at 17:21