https://kotlinlang.org logo
Title
v

Vitali Plagov

09/09/2020, 6:55 PM
Hello. I'm trying to use
datetime
library for the following scenario. Can you please help me with it? I need an object with date of now with time at 10:00. Next, I need to change this object by adding one day or by subtracting one day (depending on a certain condition). So, I made the first part:
var todayAtTen = Clock.System.todayAt(TimeZone.UTC).atTime(hour = 10, minute = 0)
but can't make a second. How can I modify this object by adding one day to it?
l

louiscad

09/09/2020, 6:57 PM
Why modify the object? Just create a new one with the time difference you need. Immutability is safer.
v

Vitali Plagov

09/09/2020, 6:58 PM
Yes, I know I can do smth like this:
Clock.System.todayAt(TimeZone.UTC).plus(...).atTime(hour = 10, minute = 0)
and
Clock.System.todayAt(TimeZone.UTC).minus(...).atTime(hour = 10, minute = 0)
But I will have to repeat the same commands twice
I don't mind creating a new object, not modifying the existing one. I just want to avoid repeating
Clock.System....
chain several times because the diff in above two chains is
minus()
and
plus()
functions
m

molikuner

09/09/2020, 7:07 PM
You could use let:
Clock.System.todayAt(TimeZone.UTC).let {
  if (condition) {
    it.plus(...)
  } else {
    it.minus(...)
  }
}.atTime(hour = 10, minute = 0)
2
v

Vitali Plagov

09/09/2020, 7:23 PM
Hm, this looks interesting. I will check. Thanks for suggestion @molikuner