Ramon J Romero y Vigil Ramon J Romero y Vigil - 3 months ago 40
Scala Question

Adding Scala Concurrent Duration To a DateTime

How do I add a

to some Java/Scala representation of time to get a time in the future/past?

I really like how scala
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.


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)

  implicit class RichDateTime(val localDateTime: LocalDateTime) extends AnyVal {
    def +(duration: Duration): LocalDateTime = {

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

scala> LocalDateTime.now + (1 minute)
warning: there was one feature warning; re-run with -feature for details
res15: java.time.LocalDateTime = 2016-10-22T16:44:46.787