0

I'm looking to do a difference between an schedule and Integer (this Integer is a number of hours).

I'm looking to compute number hours and minutes. I would like display

How can I change my code to compute hours and minutes ?

vero
  • 1,005
  • 6
  • 16
  • 29
  • What is formatter? Why is it once "12:32:44", then "11:32:46"? What is given? Where is the "7H:32min" in your code? – user unknown Mar 29 '18 at 09:56

1 Answers1

1

Possible approach with comments inside

import java.time.temporal.ChronoUnit
import java.time.LocalTime

import scala.concurrent.duration._

val t = LocalTime.now()


def toEnd(t: LocalTime) = {
  // start of the day
  val start = LocalTime.of(9, 0)
  // end of first half
  val midEnd = LocalTime.of(13, 0)
  // start of second half
  val midStart = LocalTime.of(14, 0)
  // end of the day
  val end = LocalTime.of(18, 0)


  // before start of the day
  if (t.isBefore(start)) 8.hours
  // first half
  else if (t.isBefore(midEnd)) t.until(midEnd, ChronoUnit.MILLIS).millis + 4.hours
  // in between
  else if (t.isBefore(midStart)) 4.hours
  // second half
  else if (t.isBefore(end)) t.until(end, ChronoUnit.MILLIS).millis
  // after the end
  else 0.hours
}

// here you can add any specific format for evaluated duration  
implicit class formatter(d: FiniteDuration) {
  def withMinutes = {
    // convert to minutes
    val l = d.toMinutes
    // format
    s"${l / 60}:${l % 60}"
  }
}

toEnd(t).withMinutes
toEnd(LocalTime.of(9, 30)).withMinutes
toEnd(LocalTime.of(12, 30)).withMinutes
toEnd(LocalTime.of(13, 30)).withMinutes
toEnd(LocalTime.of(14, 30)).withMinutes
Evgeny
  • 1,760
  • 10
  • 11
  • Thanks a lot. It worked very well. Just a final question. how can I add the SECOND: I added it like this but not working: t.isBefore(midEnd)) t.until(midEnd, ChronoUnit.MILLIS, ChronoUnit.SECONDS).millis.SECONDS + 4.hours – vero Mar 29 '18 at 10:44
  • You do not need to change `toEnd` itself. It returns duration with milliseconds precision. Just add another format method to `implicit class`. Like `def ttt = s"${d.toHours}:${d.toMinutes % 60}:${d.toSeconds % 60}"`, And then just use `toEnd(LocalTime.of(9, 30)).ttt` – Evgeny Mar 29 '18 at 10:47
  • Thank you very much @Evgeny – vero Mar 29 '18 at 11:05
  • I asked a question is similar to this one, the difference just a function is ToStart. I have a fault in 2 cases. Can you look it please ? Thank you https://stackoverflow.com/questions/49555595/datetime-difference-between-hour-and-integer – vero Mar 29 '18 at 12:06