Parse Exception: For our application, we would have obtained date inputs. If the user enters a different format other than specified, an Invalid Date Exception occurs and the program is interrupted. To avoid that, handle the exception and prompt the user to enter the right format as specified.
Create a driver class called Main. In the main method, Obtain start time and end time for stage event show, if an exception occurs, handle the exception and notify the user about the right format.
Input format:
The input consists of the start date and end date.
The format for the date is dd-MM-yyyy-HH:mm:ss
Output format:
Refer sample Input and Output for formatting specifications
Note: All text in bold corresponds to the input and rest corresponds to the output.
Sample Input and Output 1:
Enter the stage event start date and end date
27-01-2017-12
Input dates should be in the format ‘dd-MM-yyyy-HH:mm:ss’
Sample Input and Output 2:
Enter the stage event start date and end date
27-01-2017-12:0:0
28-01-2017-12:0:0
Start date:27-01-2017-12:00:00
End date:28-01-2017-12:00:00
Solution
import java.util.*;
import java.io.*;
import java.text.*;
class Main{
public static void main(String[] args) {
try {
// sauravhathi
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the stage event start date and end date");
String startDate = br.readLine();
String endDate = br.readLine(); // sauravhathi
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-HH:mm:ss");
Date start = sdf.parse(startDate);
Date end = sdf.parse(endDate); // sauravhathi
System.out.println("Start date: "+sdf.format(start));
System.out.println("End date: "+sdf.format(end));
} catch (ParseException e) {
// sauravhathi
System.out.println("Input dates should be in the format 'dd-MM-yyyy-HH:mm:ss'");
} catch (Exception e) {
System.out.println("Input dates should be in the format 'dd-MM-yyyy-HH:mm:ss'");
}
}
// sauravhathi
}
Happy Learning – If you require any further information, feel free to contact me.