Search code examples
androidkotlinandroid-datepicker

How to set date 1 year from current date?


I want to add exact 1 year into my current date. How to achieve this?

I've tried this:

fun getDefaultNextYearDate(): Date {
            val cal = Calendar.getInstance()
            cal.time = Date() //current date
            cal.add(Calendar.YEAR, Calendar.YEAR + 1)
            return cal.time
        }


val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'", Locale.getDefault())
val nextYearDate = sdf.parse(sdf.format(Api.getDefaultNextYearDate()))

But this will add 2 years from now for some reason (07/03/2021)


Solution

  • Calendar.YEAR is a field number indicating the year for the Calendar. Its value is 1. So, when you do this:

    cal.add(Calendar.YEAR, Calendar.YEAR + 1)
    

    The first parameter is the field you want to update(field 1, the YEAR), the second one is the amount you want to add to this property, and at this point you are saying that you want to add Calendar.YEAR(1) + 1, so, you are adding 2 to the year of this calendar.

    Just do this:

    cal.add(Calendar.YEAR, 1)
    

    and you'll have what you are expecting.