简体   繁体   English

如何在小时,分钟和秒的时间内将字符串转换为Date对象

[英]How to convert a String to a Date object for hours, minutes, and seconds

I am trying to convert a user-inputted String into hours, minutes, and seconds stored inside a Date object. 我试图将用户输入的字符串转换为存储在Date对象中的小时,分​​钟和秒。 Some code was borrowed from StackOverflow that uses a SimpleDateFormat object to parse the user input, but when it tries I get a ParseException. 从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();
}

Exception 例外

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)

Take a look at your format compared to what is been entered... 与输入的内容相比,看一下您的格式...

kk-mm-ss
01:02:03

See the difference? 看到不同? Your format is expecting - , but you're providing : 您的格式应为- ,但您要提供:

Change kk-mm-ss to kk:mm:ss kk-mm-ss更改为kk:mm:ss

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM