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 :-
- getCalculatedMonths(0) -> 2022-05
- getCalculatedMonths(1) -> 2022-04
- getCalculatedMonths(-1) -> 2022-06
- getCalculatedMonths(2) -> 2022-03
- getCalculatedMonths(-2) -> 2022-07