41

Having val hm: HashMap[org.joda.time.DateTime, MyType] I am trying to get the first and the last DateTime of the set by means of hm.keys.min and hm.keys.max respectively but the compiler says No implicit Ordering defined for org.joda.time.DateTime. How to define this ordering (both implicit and explicit options are interesting)?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Ivan
  • 63,011
  • 101
  • 250
  • 382

2 Answers2

102
object Joda {
    implicit def dateTimeOrdering: Ordering[DateTime] = Ordering.fromLessThan(_ isBefore _)
}

// elsewhere
import Joda._
dateTimes.sorted
retronym
  • 54,768
  • 12
  • 155
  • 168
17

To facilitate working with Joda DateTime in Scala, nscala-time was created: https://github.com/nscala-time/nscala-time

After including it in your project with

libraryDependencies += "com.github.nscala-time" %% "nscala-time" % "1.8.0"

you can just import OrderingImplicits. Either all at once:

import com.github.nscala_time.time.OrderingImplicits._

or a particular one:

import com.github.nscala_time.time.OrderingImplicits.DateTimeOrdering
Majki
  • 618
  • 7
  • 14