Ivan
Ivan

Reputation: 64227

How to cast Long to Int in Scala?

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?

Upvotes: 47

Views: 56256

Answers (1)

Luigi Plinge
Luigi Plinge

Reputation: 51109

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

Upvotes: 85

Related Questions