Martin
Martin

Reputation: 2914

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)

Upvotes: 1

Views: 3226

Answers (3)

Leonardo Velozo
Leonardo Velozo

Reputation: 648

Calendar.add() takes two parameters, first one is the unity of what you want to add, and second one is the quantity. So you need to replace cal.add(Calendar.YEAR, Calendar.YEAR + 1) for cal.add(Calendar.YEAR, 1);

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

Upvotes: 0

Roland
Roland

Reputation: 23262

You are adding Calendar.YEAR and +1 to your current year. As Calendar.YEAR is a constant with value 1 you are adding in fact 2 years.

You may also want to have a look at the java.time-API instead. Your example could look as simple as:

fun getDefaultNextYearDate() = LocalDateTime.now().plusYears(1)

Upvotes: 0

Massita
Massita

Reputation: 309

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.

Upvotes: 3

Related Questions