Java Android:如何获取/将 long 转换为 int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21742268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:26:35  来源:igfitidea点击:

Android: How to get/convert long to int?

javaandroidintlong-integer

提问by dudzio

Calendar c = Calendar.getInstance(); 

long diff = c.getTimeInMillis() - DateSaved.getTimeInMillis(); //result in millis

long daysDiff =  (diff / (24 * 60 * 60 * 1000));

Everything works fine, when i print diff (integer number of days)...

一切正常,当我打印差异(天数)...

The problem starts here:

问题从这里开始:

int daysDiffINT = (int) daysDiff; 
int daysRemaining = (sumaINT/dailyINT) - daysDiffINT;

i need to proceed my long diff with some int values.

我需要用一些 int 值来处理我的长差异。

This above doesn't work.The console gives me an error: "Invalid int" I searched a little bit, there are thousands of converting String to Int etc.

上面的这不起作用。控制台给了我一个错误:“Invalid int”我搜索了一下,有数千个将 String 转换为 Int 等。

But how can I get int from long? Or String from long?

但是我怎样才能从 long 中得到 int 呢?还是从长字符串?

It's driving me crazy :(

这让我疯狂 :(

// BIG Thanks for all of you - you've learned me how to make my own app :)

// 非常感谢你们所有人 - 你们已经学会了如何制作我自己的应用程序 :)

采纳答案by Piotr ?lesarew

long to int:

长到整数:

public static int safeLongToInt(long l) {
    if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (l + " cannot be cast to int without changing its value.");
    }
    return (int) l;
}

long to String:

长到字符串:

public static String longToString(long l) {
        return String.valueOf(l);
}