Home > Software engineering >  How to generate dates of between 2 dates in Android
How to generate dates of between 2 dates in Android

Time:08-01

In my application I want get dates between 2 date and for this I write below codes.
But when show current date miss today!
For example today is 2022-07-31 but show me 2022-07-30!
My code is :

private fun getDatesBetween(): MutableList<String> {
    val dates = ArrayList<String>()
    val input = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
    var date1: Date? = null
    var date2: Date? = null
    val sdf = SimpleDateFormat("yyyy-MM-dd")
    val currentDate = sdf.format(Date())
    try {
        date1 = input.parse("2020-1-1")
        date2 = input.parse(currentDate)
    } catch (e: ParseException) {
        e.printStackTrace()
    }
    val cal1 = Calendar.getInstance()
    cal1.time = date1
    val cal2 = Calendar.getInstance()
    cal2.time = date2
    while (!cal1.after(cal2)) {
        val output = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        dates.add(output.format(cal1.time))
        cal1.add(Calendar.DATE, 1)
    }
    return dates
}

I think this problem for this line :

cal1.add(Calendar.DATE, 1)

How can I fix it?

How can I fix it?

CodePudding user response:

I didn't test it, but I think that works:

add this little helper function:

private fun getDayDiff(lowerValue: Long, higherValue: Long): Int {
    val diffMillis = higherValue.minus(lowerValue)
    val cal = Calendar.getInstance()
    cal.timeInMillis = diffMillis
    return cal.get(Calendar.DAY_OF_YEAR)
}

and instead of your while loop:

repeat(getDayDiff(cal1.timeInMillis, cal2.timeInMillis)){
        cal1.add(Calendar.DATE,1)
        val output = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        dates.add(output.format(cal1.time))
    }
  • Related