0

I will use Timer() to execute function by 5 minutes in Kotlin.

And when I execute function by 5m, if a day passed,I want count var to be 0.

So my idea was

  1. declare two vars

    var todayDate = LocalDate.now() // 2019-09-23
    var todayCount:Int = 0
    
  2. After that I will check this vars in 5 minutes by using Timer()

Then todayDate value differs from previous todayDate, then I can detect date change.

However, I don't know how to compare current todayDate and previous todayDate.

Any idea? or is there any other way to know day change?

aSemy
  • 5,485
  • 2
  • 25
  • 51
Hyejung
  • 902
  • 1
  • 8
  • 22
  • 1
    Instead of tracking `todayDate` you could [use `java.time` to compute how many minutes have elapsed today](https://stackoverflow.com/questions/25736410/how-to-get-the-total-number-of-minutes-in-the-day-so-far), and if it's under 5 minutes, then reset `todayCount` – aSemy Jan 01 '23 at 15:33

1 Answers1

0

For your specific question about comparing dates you can use the isEqual() method on your LocalDate instance (docs). Something like the following would likely do what you want:

// initial state
var todayDate = LocalDate.now()
var todayCount = 0

// in each timer iteration:
val now = LocalDate.now()
if (!todayDate.isEqual(now)) {
  // it's a new day
  todayCount = 0
  todayDate = now
} else {
  // it's the same day
  ++todayCount
}

However if you're talking about Android and using its Timer class, you need to be aware that that runs on a background thread and you will need to persist your todayDate and todayCount values somewhere (which could be app preferences, your app DB, etc.).

Mark Ormesher
  • 2,289
  • 3
  • 27
  • 35