How to cast Long to Int in Scala?

Ivan picture Ivan · Oct 16, 2011 · Viewed 41k times · Source

I'd like to use the folowing function to convert from Joda Time to Unix timestamp:


def toUnixTimeStamp(dt : DateTime) : Int = {
  val millis = dt.getMillis
  val seconds = if(millis % 1000 == 0) millis / 1000
    else { throw new IllegalArgumentException ("Too precise timestamp") }

  if (seconds > 2147483647) {
    throw new IllegalArgumentException ("Timestamp out of range")
  }

  seconds
}

Time values I intend to get are never expected to be millisecond-precise, they are second-precise UTC by contract and are to be further stored (in a MySQL DB) as Int, standard Unix timestamps are our company standard for time records. But Joda Time only provides getMillis and not getSeconds, so I have to get a Long millisecond-precise timestamp and divide it by 1000 to produce a standard Unix timestamp.

And I am stuck making Scala to make an Int out of a Long value. How to do such a cast?

Answer

Luigi Plinge picture Luigi Plinge · Oct 16, 2011

Use the .toInt method on Long, i.e. seconds.toInt