【问题标题】:Converting long to int in Java在 Java 中将 long 转换为 int
【发布时间】:2015-04-27 16:00:38
【问题描述】:

我使用 System.currentTimeMillis() 来获取自纪元以来的秒数。 这是一个例子。

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

输出给出:

 >>1424876956
 >>1424876928

所以问题是转换值不匹配。我想要的是让第一个输出与整数相同。

你能提供一些背景为什么会发生这种情况吗?

【问题讨论】:

  • 该代码不应编译。 Java 中没有 int 方法。
  • 应该是(int)enable_beacon_timestamp
  • 有时,long 中的值会超过整数值允许的限制。查找 docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html 以便能够正确投射您的长。
  • @KevinAvignon 他的号码示例不超过Integer.MAX_VALUE 的2,147,483,647,所以如果他改成我上面说的应该没问题。
  • 仍然注意 Kevin Aivgnon 关于 long 可以超过 Integer 变量的最大值这一事实的评论。

标签: java casting timestamp epoch


【解决方案1】:

您的转换语法不正确。您还需要注意longs 可能比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;
}

试试这样吧……

【讨论】:

  • 很好的答案,但您还应该测试下溢(尽管在这种情况下不需要)。
  • 说得好,对于参考读者来说绝对值得一提,因为 System.currentTimeMillis() 在这种情况下已经过时了。
【解决方案2】:

你可以写一些东西,比如

try{

   int castedValue = ( enable_beacon_timestamp < (long)Integer.MAX_VALUE )?(int)enable_beacon_timestamp : -1;
   }
catch (Exception e)
{
   System.out.println(e.getMessage());
}

【讨论】:

    【解决方案3】:

    Java SE 8

    1. 为避免自己计算,您可以使用TimeUnit#convert
    2. 为避免因溢出而产生不良结果,您可以使用Math.toIntExact,如果值溢出int,则会引发异常。

    演示:

    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.");
            }
        }
    }
    

    输出:

    1621358400
    1621358400
    

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2014-03-13
      • 1970-01-01
      相关资源
      最近更新 更多