我正在尝试将用户输入的字符串转换为存储在日期对象中的小时、分钟和秒。一些代码是从 StackOverflow 借来的,它使用 SimpleDateFormat 对象来解析用户输入,但当它尝试时,我得到了 ParseException。
System.out.println("Enter the start time of the event(hh:mm:ss): ");
String input = sc.next();
SimpleDateFormat f = new SimpleDateFormat("kk-mm-ss");
Date start = new Date();
try {
start = f.parse(input);
} catch (ParseException e) {
System.out.println("ERROR: Failed to parse start time.");
e.printStackTrace();
}
异常
java.text.ParseException: Unparseable date: "01:02:03"
at java.text.DateFormat.parse(Unknown Source)
at Main.createDialog(Main.java:78)
at Main.displayMenu(Main.java:44)
at Main.main(Main.java:26)
最佳答案
将您的格式与输入的内容进行比较...
kk-mm-ss
01:02:03
看出区别了吗?您的格式需要 -
,但您提供的是 :
将 kk-mm-ss
更改为 kk:mm:ss
关于java - 如何将字符串转换为表示小时、分钟和秒的日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26209456/