import java.io.Console;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* A simple class to demonstrate taking a String representing a date in
* the format MM-DD-YYYY and creating a Date object from it.
* @author astjohn
*
*/
public class DateExample
{
public static void main(String[] args)
{
// use a console for interaction (run this from the command line)
Console console = System.console();
// if there is no available console, exit the program
if (console == null)
{
System.out.println("No console: non-interactive mode!");
System.exit(0);
}
// otherwise, ask the user to enter a date
System.out.print( "Enter a date in the format MM-DD-YYYY, as in 04-30-2018: " );
// read input from the console
String dateString = console.readLine();
// create a simple date format object for parsing dates of the form MM-DD-YYYY
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
// attempt to parse the date
try
{
// the parse method throws a ParseException if it's not formatted correctly
Date date = dateFormat.parse( dateString );
// print the date back out
System.out.println( "You entered the date: " + date.toString() );
}
catch (ParseException e)
{
System.out.println( "\nOops, that's not a validly formatted date!");
}
}
}