1

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..

  • Does this answer your question? [Android - Date in API level 21](https://stackoverflow.com/questions/60687806/android-date-in-api-level-21) Does [this](https://stackoverflow.com/questions/68191152/convert-string-date-to-date-in-android-java-kotlin-without-having-to-deal-with)? – Ole V.V. May 18 '22 at 05:51
  • thanks for answering , can you tell me how we get previous and next 5 months without using LocalDate class @OleV.V. ? – Surajkaran Meghwanshi May 20 '22 at 07:07
  • I am afraid that I would be doing you and those maintaining your code after you a very ill favour if i did. IMO you should rather give desugaring and `LocalDate` a good thought. – Ole V.V. May 20 '22 at 07:40

1 Answers1

1

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