-2

I'm using System.currentTimeMillis() for getting seconds since the epoch. This is an example.

 long enable_beacon_timestamp = System.currentTimeMillis()/1000;
 println(enable_beacon_timestamp);
 println(int(enable_beacon_timestamp));      
 enable_beacon(int(enable_beacon_timestamp));

And the output gives:

 >>1424876956
 >>1424876928

So the problem is that there is a mismatch in cast value. What I want is to get the first output the same as the integer.

Can you provide some background why this happen?.

progloverfan
  • 155
  • 2
  • 13

3 Answers3

1

Your cast syntax is incorrect. You need also be aware that longs can be much bigger that the max value for int.

int y;
if ( enable_beacon_timestamp > (long)Integer.MAX_VALUE ) {
    // long is too big to convert, throw an exception or something useful
}
else {
    y = (int)enable_beacon_timestamp;
}

Try something like this perhaps...

Dragan
  • 455
  • 4
  • 12
  • Good answer but you should also test for underflow (albeit not required in this case). – Bathsheba Feb 25 '15 at 15:43
  • Good remark, definitely worth mentioning for reference readers tho System.currentTimeMillis() makes it obsolete to do so in this case. – Dragan Feb 25 '15 at 15:46
0

you could write something such as

try{

   int castedValue = ( enable_beacon_timestamp < (long)Integer.MAX_VALUE )?(int)enable_beacon_timestamp : -1;
   }
catch (Exception e)
{
   System.out.println(e.getMessage());
}
Kevin Avignon
  • 2,853
  • 3
  • 19
  • 40
0

Java SE 8

  1. To avoid doing the calculations yourself, you can use TimeUnit#convert.
  2. To avoid getting undesirable result due to overflow, you can use Math.toIntExact which throws an exception if the value overflows an int.

Demo:

import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        long seconds = TimeUnit.SECONDS.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        System.out.println(seconds);

        try {
            int secondInt = Math.toIntExact(seconds);
            System.out.println(secondInt);
            // ...
        } catch (ArithmeticException e) {
            System.out.println("Encountered error while casting.");
        }
    }
}

Output:

1621358400
1621358400
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110