异常:java.lang.NumberFormatException 将 String 转换为 long 时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18562081/
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-12 09:03:53  来源:igfitidea点击:

Exception : java.lang.NumberFormatException When convert String to long

java

提问by N Sharma

I am converting the string which have '1520056800` to long to have date. But I am getting NumberFormatException to convert this

我正在将具有 '1520056800` 的字符串转换为 long 以获取日期。但我得到 NumberFormatException 来转换这个

Please help me.

请帮我。

long expiryDateMS = Long.parseLong(responseArray[0].replaceAll(" ", ""));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = new Date(expiryDateMS);

Stack trace

堆栈跟踪

09-02 00:52:28.984: E/AndroidRuntime(12025): Caused by: java.lang.NumberFormatException: 1520056800
09-02 00:52:28.984: E/AndroidRuntime(12025):    at java.lang.Long.parse(Long.java:353)
09-02 00:52:28.984: E/AndroidRuntime(12025):    at java.lang.Long.parseLong(Long.java:344)
09-02 00:52:28.984: E/AndroidRuntime(12025):    at java.lang.Long.parseLong(Long.java:311)
09-02 00:52:28.984: E/AndroidRuntime(12025):    at com.example.astrill_openvpn.MainOnOffActivity.onCreate(MainOnOffActivity.java:99)
09-02 00:52:28.984: E/AndroidRuntime(12025):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-02 00:52:28.984: E/AndroidRuntime(12025):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

回答by Martijn Courteaux

This code should do the job. So I'm guessing you have got some encoding/special character problem. Try this to verify you have a real ASCII encoded number:

这段代码应该可以完成这项工作。所以我猜你有一些编码/特殊字符问题。试试这个来验证你有一个真正的 ASCII 编码数字:

String str = responseArray[0].replaceAll(" ", "");
for (int i = 0; i < str.length(); ++i)
{
    char a = str.charAt(i);
    if (!('0' <= a && a <= '9')) System.out.println(a + " is not a valid digit!");
}

回答by Jesko R.

You probably have invisible or invalid characters in the string. Try this postfor more details.

您可能在字符串中有不可见或无效的字符。试试这个帖子了解更多细节。