Home > Software engineering >  Filter the arraylist by subtracting with minutes in kotlin
Filter the arraylist by subtracting with minutes in kotlin

Time:12-23

i have an list of object , in that object i have a value timestamp and it is in "Timestamp": "2021-12-16T07:30:13.950774575Z",this format. I have a requirement when i click on a textview named 60 mins , i should get the data for 60 mins from end time , that is if i have data between 4pm to 7pm , on on click i need data from 6pm to 7pm . That is need to subtract 1 hour and filter the data, i have tried but i didn't get proper solution, can anyone help me how can it be achieved . Please help me as i am a beginner .

CodePudding user response:

Put all your data in a list and then filter the list for the elements within the last 60 minutes.

var now = currentTS();
var l = listOf(parseTS("2021-12-16T07:30:13.950774575Z"), parseDate(...),...);
var result = l.filter { it.inMinutes() - now.inMinutes() < 60 }

I don't know which sort of timestamp class you are using, so adjust currentTS, parseTS, inMinutes to your needs.

CodePudding user response:

I would use java.time and …

  • parse the String received from a button click (mocked, of course)
  • subtract precisely one hour from the value
  • use the result in order to filter from an example list

Here it is, all in a fun main, read the comments, please:

fun main(args: Array<String>) {
    // your example String received on button click
    val timestamp = "2021-12-16T07:30:13.950774575Z"
    // example values to be filtered
    val someObjects = listOf(
        SomeObject(0, "2021-12-12T07:30:13.950774575Z"),
        SomeObject(1, "2021-12-13T07:30:13.950774575Z"),
        SomeObject(2, "2021-12-13T07:30:13.950774575Z"),
        SomeObject(3, "2021-12-14T07:30:13.950774575Z"),
        SomeObject(4, "2021-12-15T07:30:13.950774575Z"),
        // here's the border
        SomeObject(5, "2021-12-16T07:30:13.850774575Z"),
        SomeObject(6, "2021-12-16T07:30:13.960774575Z"),
        SomeObject(7, "2021-12-17T07:30:13.950774575Z"),
        SomeObject(8, "2021-12-18T07:30:13.950774575Z")
    )
    // parse the timestamp captured on button click and subtract an hour
    val filterByOdt = OffsetDateTime.parse(timestamp).minusHours(1)

    // filter the list using the OffsetDateTime
    val filteredObjects = someObjects.filter {
        OffsetDateTime.parse(it.timestamp)
        .isBefore(filterByOdt)
    }

    // print the ids of the results
    println(filteredObjects.joinToString(", ") { "${it.id}" })
}

I used the following dummy class in the example.

data class SomeObject(val id: Long, val timestamp: String)

As desired, the filtered list only contains the 5 SomeObjects with a timestamp before timestamp:

0, 1, 2, 3, 4
  • Related