TashM TashM - 4 months ago 8x
Java Question

Java Input String into Time

How can I make a Java program so that, in a console application, if the user were to enter a time (say 13:00) as a String with the Scanner, I can turn this String into a time object that can be used for maths.

Any ideas or am I in way over my head?


In my app, charges apply for different times (extra for night time etc). I need to be able to get the numbers from a String (or Double, I'm flexible)


You need to do a couple of things first, like giving a hint to the user about how the input time can look like... So I would do:

  1. Define the input format for the time
  2. Give a hint to the user about it
  3. Parse the input to the format you defined
  4. And finally manipulate the date as you need it


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String format = "HH:mm:ss";
System.out.println("Please give the desired time in this fomrat HH:mm:ss ...");
String inp = s.nextLine();
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
    Date date = sdf.parse(inp);
    System.out.println("this is the date:" + date);
} catch (ParseException e) {
    System.err.println("invalid date...");