【发布时间】:2017-08-27 04:27:40
【问题描述】:
所以我想扩展这个方法,让用户输入一个有效的 12 小时时间。我有它,它工作正常。但我想要它,如果小时超过 12 小时或分钟超过 59,那么它会提示再次执行此操作。但现在它只会通过添加时间来转换时间。 还有更有效的方法来写这个吗? (就像没有 Date newTime = sdf.parse(startTime); 让用户只需输入一个字符串并让它检查它的格式是否正确?
public static void userInput(){
Scanner in = new Scanner(System.in);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
String startTime;
System.out.print("What is the start time?: ");
boolean success = false;
while (success != true){
try{
startTime = in.nextLine();
Date newTime = sdf.parse(startTime);
startTime = sdf.format(newTime);
System.out.println(startTime);
success = true;
}
catch(Exception e){
System.out.println("Not a valid time. Please use this format (HH:MM AM)");
}
}
}
【问题讨论】:
-
Date和SimpleDateFormat现在是旧版,被 java.time 类取代(巨大改进)。
标签: java date time format simpledateformat