You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中String转int失败:时间转整数触发NumberFormatException报错

解决java.lang.NumberFormatException: For input string: "4:12:31"问题

嘿,我一眼就看出问题出在哪啦!你最后一行代码里,把hours+":"+minutes+":"+seconds拼接成了带冒号的时间字符串(比如"4:12:31"),而Double.parseDouble()根本无法解析带冒号的内容,这就是抛出NumberFormatException的核心原因。

你想要把当前时间转成Integer,应该是想得到HHmmss格式的数字(比如41231),或者当天已过的总秒数,下面给你两种对应的正确实现方式:

方式一:转成HHmmss格式的整数

这种方式会把时间转换成类似小时*10000 + 分钟*100 + 秒的整数,比如凌晨4点12分31秒就是41231:

long unixTime = System.currentTimeMillis() / 1000L; 
Date time = new java.util.Date(unixTime * 1000); 
Calendar cal = Calendar.getInstance(); 
cal.setTime(time); 
int hours = cal.get(Calendar.HOUR_OF_DAY); 
int minutes = cal.get(Calendar.MINUTE); 
int seconds = cal.get(Calendar.SECOND); 
// 用数学运算直接拼接成整数,彻底避免字符串解析问题
int currentTime = hours * 10000 + minutes * 100 + seconds;

方式二:转成当天已过的总秒数

如果你的需求是计算当天已经流逝了多少秒,直接用时间单位换算即可:

long unixTime = System.currentTimeMillis() / 1000L; 
Date time = new java.util.Date(unixTime * 1000); 
Calendar cal = Calendar.getInstance(); 
cal.setTime(time); 
int hours = cal.get(Calendar.HOUR_OF_DAY); 
int minutes = cal.get(Calendar.MINUTE); 
int seconds = cal.get(Calendar.SECOND); 
// 计算总秒数:1小时=3600秒,1分钟=60秒
int currentTime = hours * 3600 + minutes * 60 + seconds;

额外推荐:用Java 8+新时间API简化代码

如果你用的是Java 8及以上版本,推荐使用更简洁的java.time包,代码可读性更高,还能避免Calendar的一些坑:

// 获取当前时间
LocalTime now = LocalTime.now();
// 转HHmmss格式整数
int hhmmss = now.getHour() * 10000 + now.getMinute() * 100 + now.getSecond();
// 转当天总秒数
int totalSeconds = now.toSecondOfDay();

内容的提问来源于stack exchange,提问作者nihel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:28:13