Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 629
Ivan Avatar asked Oct 16 '11 05:10

Ivan


People also ask

How do I cast a value to an int?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

What is a long Scala?

In Scala, Long is a 64-bit signed integer, which is equivalent to Java's long primitive type. The &(x: Long) method is utilized to return the Bitwise AND of the specified Long value and Long value. Method Definition – def &(x: Long) Returns – Returns the Bitwise AND of this value and x.


1 Answers

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

like image 173
Luigi Plinge Avatar answered Sep 28 '22 08:09

Luigi Plinge