3

How do I add a scala.concurrent.Duration to some Java/Scala representation of time to get a time in the future/past?

I really like how scala Duration adds methods to integers (e.g. 10 seconds), so I'm trying to do something of the form:

import java.time.LocalDateTime

val futurePoint: LocalDateTime = LocalDateTime.now + (10 Seconds)

I would prefer not use other libraries as suggested in this answer, I'm trying to stick with Java/Scala language libraries.

Ramón J Romero y Vigil
  • 17,373
  • 7
  • 77
  • 125

1 Answers1

5

You can accomplish this using an implicit class and which adds methods to LocalDateTime:

import java.time.LocalDateTime
import java.time.{Duration => JDuration}

import scala.concurrent.duration._

object M {
  def main(args: Array[String]): Unit = {
    val futurePoint: LocalDateTime = LocalDateTime.now + (10 seconds)
    println(futurePoint)
  }

  implicit class RichDateTime(val localDateTime: LocalDateTime) extends AnyVal {
    def +(duration: Duration): LocalDateTime = {
      localDateTime.plus(JDuration.ofMillis(duration.toMillis))
    }
  }
}

Now you can run the following (warning is because of the use of infix notation):

scala> LocalDateTime.now + (1 minute)
res15: java.time.LocalDateTime = 2016-10-22T16:44:46.787
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321