Home > Enterprise >  Find current month , previous month and next month in kotlin android studio in API level 26
Find current month , previous month and next month in kotlin android studio in API level 26

Time:05-26

Any method to get current month , 5 previous month and 5 next months which is also work on android 6 . I am using LocalDate Class which is perfect works on above Android 8 API level 26.

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



    viewModel.selectedMonth.value = getCalculatedMonth("2022-05-17" , month_value)

here month_value is -> 0 for current month 1 for next month -1 for previous month

But problem is that it only support in above android version 8. is any other method to get previous , current and next month under API level 26.

if have any solution please comment your answer..

CodePudding user response:

I found the answer this which also work perfect in under android version 8

Use this method

@SuppressLint("SimpleDateFormat")
fun getCalculatedMonths( month: Int): String? {
    val c: Calendar = GregorianCalendar()
    c.add(Calendar.MONTH, -month)
    val sdfr = SimpleDateFormat("yyyy-MM")
    return sdfr.format(c.time).toString()
}

Here i getting result like this :-

  1. getCalculatedMonths(0) -> 2022-05
  2. getCalculatedMonths(1) -> 2022-04
  3. getCalculatedMonths(-1) -> 2022-06
  4. getCalculatedMonths(2) -> 2022-03
  5. getCalculatedMonths(-2) -> 2022-07
  • Related