The answer by A4L is correct. But as Jon Skeet commented, you really should use Joda-Time. The java.util.Date/Calendar classes are notoriously bad, and are being supplanted in Java 8 by the java.time.* classes whose design is inspired by Joda-Time.
Be aware that unlike java.util.Date, a org.joda.time.DateTime knows its time zone.
Here's the Joda-Time version of A4L's example code.
You can choose or define other formats for parsing. I went with the standard ISO 8601 format.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
Scanner sc = new Scanner(System.in);
DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
// A good practice is to always specify a time zone rather than depend on default.
parser = parser.withZone( DateTimeZone.forID( "America/New_York" ) );
System.out.println("Please enter a date (" + "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" + "): ");
String dateString = sc.next();
DateTime dateTime = null;
try {
dateTime = parser.parseDateTime(dateString);
System.out.println( "dateTime: " + dateTime.toString() );
} catch ( IllegalArgumentException e ) {
// e.printStackTrace();
System.out.println( "The date you entered cannot be parsed." );
}
sc.close();
When run…
Please enter a date (yyyy-MM-dd'T'HH:mm:ss.SSSZZ):
2013-12-13T23:45
dateTime: 2013-12-13T23:45:00.000-05:00