I want to get next 5 years after from now and i am using this below code . It work fine in above android version 8 device .

@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("SimpleDateFormat")
fun getCalculatedYear(date: String, month: Int): String? {
    val ld = LocalDate.parse(date)
    val currentMonth = ld.minusYears(month.toLong())
    Timber.tag("currentMonth").d(currentMonth.toString())
    var dateFormat = SimpleDateFormat("yyyy-MM-dd")
    val newDate = dateFormat.parse(currentMonth.toString())
    dateFormat = SimpleDateFormat("yyyy")
    return dateFormat.format(newDate!!)
}

Is there any solution to get this in all android version device.

Edited

Found solution with below code

@SuppressLint("SimpleDateFormat")
fun getCalculatedYears( year: Int): String? {
    val c: Calendar = GregorianCalendar()
    c.add(Calendar.YEAR, -year)
    val sdfr = SimpleDateFormat("yyyy")
    return sdfr.format(c.time).toString()
}
2

There are 2 answers

0
Surajkaran Meghwanshi On

this helps me to find previous and next years

@SuppressLint("SimpleDateFormat")
fun getCalculatedYears( year: Int): String? {
    val c: Calendar = GregorianCalendar()
    c.add(Calendar.YEAR, year)
    val sdfr = SimpleDateFormat("yyyy")
    return sdfr.format(c.time).toString()
}
0
Praveen On

You can use Java 8+ APIs like Time Date API in Android 8 and below, by enabling coreLibraryDesugaring

To enable API desugaring

In your module level build.gradle, add coreLibraryDesugaringEnabled = true to compileOptions

android {
    //..

    compileOptions {
            coreLibraryDesugaringEnabled = true

            //..
        }

    //..
}

Now add coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:1.1.5" to dependencies of the same build.gradle

dependencies {
    coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:1.1.5"
    //..
}

I want to get next 5 years after from now and i am using this below code

I didn't quite understand, how you're able to add 5 years to the passed date using your code, but you can easily do it using Time Date API like this

fun addYears(date: String): String? {
    val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    var ld = LocalDate.parse(date, dateFormatter)
    ld = ld.plusYears(5L)
    return ld.year.toString()
}