A Scala nscala-time example (days to Christmas)

I woke up this morning (June 7, 2013) thinking it must be about 200 days to Christmas. Foregoing any simple ways to determine that, I decided it would be a good time to use the nscala-time library, a Scala wrapper around Joda Time.

Sticking with the time theme, I haven’t much free time today, so without further ado, here is some Scala code that determines the number of days between today and Christmas:

import com.github.nscala_time.time.Imports._
import org.joda.time.Days

// from http://alvinalexander.com
object DaysUntilChristmas extends App {

    // 1: get the current date and time
    val now = DateTime.now
    // 2: get a date to represent Christmas
    val xmas = (new DateTime).withYear(2013)
    // 3: determine the number of days from now until xmas
    val daysToXmas = Days.daysBetween(now, xmas).getDays
    // 4: print the result
    println(s"daysToXmas = $daysToXmas")

    // bonus: what day is 200 days from now?
    val nowPlus200 = now + 200.days
    println(s"nowPlus200 = $nowPlus200")


On the morning of June 7, 2013 (in Boulder, Colorado time), the output from this code is:

daysToXmas = 201
nowPlus200 = 2013-12-24T10:29:12.564-07:00

Creating Christmas

If the way I created an instance of Christmas looks a little longer than need be, I did first try to create it like this:

val xmas = new DateTime(2013, 12, 25, 1, 1)

The last two fields of that constructor specify the hour and minute, and when I used that approach, I got one day less than the “fluent” style I showed first. When I changed the hour to something later in the day, such as 12 or 15, etc., I got the same result as the fluent style, so the result depended on the hour I used. Since I wasn’t interested in that level of detail, I went with the fluent style.

A little more information

If you want to have a little more nscala-time fun, add this loop to the bottom of the program:

for (i <- 1 to 203) {
    val d = now.plusDays(i)
    println(f"$i%3d: $d")

On June 6, 2013, that prints results like this:

1: 2013-06-08T10:29:12.564-06:00
2: 2013-06-09T10:29:12.564-06:00
3: 2013-06-10T10:29:12.564-06:00

-- much more here --

199: 2013-12-23T10:29:12.564-07:00
200: 2013-12-24T10:29:12.564-07:00
201: 2013-12-25T10:29:12.564-07:00

No matter how you count it, 201 does seem to be the correct result.

Using nscala-time with Scala and SBT

To use the nscala-time library with a Scala SBT project, just add this line to your SBT build.sbt file:

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

With that line, you should be able to copy and paste the source code above into an SBT project, and run it like this:

$ sbt run

If you needed a Scala + nscala-time example, I hope this has been helpful.