46

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?

Ivan
  • 63,011
  • 101
  • 250
  • 382

1 Answers1

84

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

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
  • 1
    `.toInt` is better than `asInstanceOf[Int]`. what was I thinking. – Eugene Yokota Oct 16 '11 at 05:27
  • Looks like it works. Compiles at least. Perhaps I need to have some sleep... :-] – Ivan Oct 16 '11 at 05:30
  • @eugene-yokota, would you be so kind to explain why is .toInt better than asInstanceOf[Int]? Intuitively it seems obvious, but I am curious to know. – Ivan Oct 16 '11 at 05:34
  • 4
    @Ivan, because `toInt` is still within the means of Scala standard library (and hopefully with good optimizations and checking etc) whereas `asInstanceOf` is like opening the emergency escape hatch while the plane is in midair. – Eugene Yokota Oct 16 '11 at 05:56
  • 11
    @Ivan casts are inherently not typesafe. E.g. `class Foo; (new Foo).asInstanceOf[Int]` compiles, but throws a `ClassCastException` at runtime. So using a cast, you're losing the benefit of static type checking at compile time. – Luigi Plinge Oct 16 '11 at 07:14
  • Yes, but is it efficient, or does it box? – Scott Carey Jan 06 '15 at 04:05
  • @ScottCarey yes it is efficient. These enrichments (RichLong etc) are value classes, so effectively you're using a static method. You can rely on the Scala library writers to have thought of this kind of thing. – Luigi Plinge Jan 07 '15 at 00:22
  • Does it throw an exception for values bigger than Integer.MAX_VALUE? Something like guava's Ints.checkedCast(long) ? - http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/primitives/Ints.html#checkedCast(long) – raisercostin Jan 27 '15 at 07:18
  • @raisercostin No it does not. In that respect it follows all other Java arithmetic, i.e. bounds-checking is sacrificed for performance. However it's trivial to write such a method yourself. – Luigi Plinge Jan 27 '15 at 18:13