kotlintimemilliseconds

How to get data by milliseconds that is from the current week?


I have a database with some data, where each data has a timestamp in milliseconds.

I need to get data from the databse for the current week. I have a week chart and need to show data for current week.

I tried to google but didn't find anything sutable to my use case.


Solution

  • I'll illustrate an answer based on some data.

    The milliseconds you talk of - that must be relative to some 0 point, or Epoc. Assuming this is the "Unix epoc" you can (1) use the java.time.Instant to convert the milliseconds into an Epoc, and then you can convert into one of the many date/time classes, e.g. ZoneDateTime (2) for which you need to pick a time zone (3)

    Then you need to work out when the beginning of the week is for you. You say Monday, but midnight on that day? and in what timezone. Assuming again UTC timezone and at (5) we "chop off" the hours/minutes/etc from "now" to get midnight for the current day then at (6) we wind back to the previous Monday.

    Now I at (7) we can filter to limit the dataset to "this week's data":

    fun main(args: Array<String>) {
    
        // https://www.epochconverter.com/
        val data = listOf(
            Data(1711916054000L, "Apples"), // Sunday, 31 March 2024 20:14:14 GMT
            Data(1712002454000L, "Orange"), // Monday, 1 April 2024 20:14:14 GMT
            Data(1712175254000L, "Pears"), // Tuesday, 2 April 2024 20:14:14 GMT
        )
    
        println("Raw data")
        data.forEach {
            it.datetime = ZonedDateTime.ofInstant( // (2)
                Instant.ofEpochMilli(it.millis), // (1)
                ZoneOffset.UTC) // (3)
            println(it)
        }
        println()
    
        val startOfThisWeek = ZonedDateTime.now(ZoneOffset.UTC) // (4)
            .truncatedTo(ChronoUnit.DAYS) // (5)
            .with(TemporalAdjusters.previous(DayOfWeek.MONDAY)) // (6)
        println("Data for this week, where this week starts on $startOfThisWeek")
    
        data.filter { startOfThisWeek <= it.datetime }  // (7)
            .forEach { println(it) }
    
    }
    
    data class Data(val millis:Long, val thing: String, var datetime: ZonedDateTime? = null)
    

    Output is

    Raw data
    Data(millis=1711916054000, thing=Apples, datetime=2024-03-31T20:14:14Z)
    Data(millis=1712002454000, thing=Orange, datetime=2024-04-01T20:14:14Z)
    Data(millis=1712175254000, thing=Pears, datetime=2024-04-03T20:14:14Z)
    
    Data for this week, where this week starts on 2024-04-01T00:00Z
    Data(millis=1712002454000, thing=Orange, datetime=2024-04-01T20:14:14Z)
    Data(millis=1712175254000, thing=Pears, datetime=2024-04-03T20:14:14Z)