views:

131

answers:

2

What's the standard way to work with dates and times in Scala? Should I use Java types such as java.util.Date or there are native Scala alternatives?

A: 

It is the custom to use Java's types.

Vadim Shender
That is the question - If it is the custom, what is the native way?
Ivan
+14  A: 

Joda Time is a good Java library, there is a Scala wrapper / implicit conversion library avaliable for Joda Time at scala-time created by Jorge Ortiz. (Note implicits have a performance hit, but it depends on what you do if you will notice. And if you run into a performence problem you can just revert to the Joda interface)

From the README:

USAGE:
  import org.scala_tools.time.Imports._

  DateTime.now
  // returns org.joda.time.DateTime = 2009-04-27T13:25:42.659-07:00

  DateTime.now.hour(2).minute(45).second(10)
  // returns org.joda.time.DateTime = 2009-04-27T02:45:10.313-07:00

  DateTime.now + 2.months
  // returns org.joda.time.DateTime = 2009-06-27T13:25:59.195-07:00

  DateTime.nextMonth < DateTime.now + 2.months
  // returns Boolean = true
  DateTime.now to DateTime.tomorrow
  // return org.joda.time.Interval =
  //   2009-04-27T13:47:14.840/2009-04-28T13:47:14.840

  (DateTime.now to DateTime.nextSecond).millis
  // returns Long = 1000

  2.hours + 45.minutes + 10.seconds
  // returns org.scala_tools.time.DurationBuilder
  // (can be used as a Duration or as a Period)

  (2.hours + 45.minutes + 10.seconds).millis
  // returns Long = 9910000 

  2.months + 3.days
  // returns Period
oluies
Video scalaj: Idiomatic Scala Wrappers for Java Librarieshttp://days2010.scala-lang.org/node/138/164
oluies
Thanks, I haven't know about this wrapper.
Vadim Shender
I can't get a formatted output from this. If I use DateTime.formatted("yyyyMMdd") I just get plain "yyyyMMdd" (letters not replaced with corresponding numbers) as response. If I use DateTime.formatted(DateTimeFormat.forPattern("yyyyMMdd")) - I get an error asking for a string argument.
Ivan
http://stackoverflow.com/questions/3639944/how-to-substract-a-day-hour-minute-from-joda-time-datetime-in-scala
oluies
artifact repo http://scala-tools.org/repo-releases/org/scala-tools/time/
oluies