【发布时间】:2020-04-22 16:19:50
【问题描述】:
我是 Java 新手。我有问题。 我有一个字符串 currentTime,其当前时间的值如下:“2204201810”。 我想将此字符串转换为整数。 错误是:
原因:java.lang.NumberFormatException:对于输入字符串:“2204201804”
但是不知道为什么Java不能转换!我的意思是字符串只包含数字而不是更多。
这是我的代码:
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
String currentTime = df.format(now.getTime());
currentTime = currentTime.replace(".", "");
currentTime = currentTime.replace(" ", "");
currentTime = currentTime.replace(":", "");
try {
int currentTimeInt = Integer.valueOf(currentTime);
} catch (NumberFormatException ex) {
//Error
}
【问题讨论】:
-
你查看
currentTime的内容了吗?我怀疑它有你期望的内容/格式 -
打印替换前后的字符串,你可能会跳过一些不能转换为
int的字符 -
我不确定下面的答案是如何工作的。运行此代码
System.out.println(currentTime);时,输出为4/22/201042AM,据我所知,它不能转换为 int、long 或 BigInteger。 -
@hooknc,那么您的操作系统中有不同的语言环境设置,它们使用斜线而不是点、逗号或冒号,并且最后还会附加 AM/PM。