I'm trying to parse an input string date to GregorianCalendar:
Scanner scan = new Scanner(System.in);
String next = scan.next("[0-9]{2}.[0-9]{2}.[0-9]{4} [0-9]{2}:[0-9]{2}");
scan.nextLine();
DateFormat df = new SimpleDateFormat("dd.MM.yyyy hh:mm");
Date date = null;
try {
date = df.parse(next);
} catch (ParseException e1) {
e1.printStackTrace();
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
System.out.println(cal.getTime());
But it keeps giving this error:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.next(Unknown Source)
Can anybody help me? This works if i don't specify the hours and minutes but not like this...
Looking at the source code of Scanner.next(Pattern)
, which is called by Scanner.next(String)
, the method roughly follows these steps:
Use the delimiter pattern to skips all the delimiters from the current position in the stream.
Search for the next delimiter in the stream. Blocks if more input is needed to find the delimiter. Continue if end of stream
Check that the pattern matches the token between the current position and the next delimiter (or end of stream).
Return the token if matches. Otherwise, throw Exception.
Since space is matched by the default delimiter pattern ("\\p{javaWhitespace}+"
), Scanner tokenizes at the date part and tries to match the token against the pattern and fails.
01.01.2014 00:00
^--------^^
token |
|
delimiter
One way is to scan them separately:
String nextDate = scan.next("[0-9]{2}\\.[0-9]{2}\\.[0-9]{4}");
String nextTime = scan.next("[0-9]{2}:[0-9]{2}");
String next = nextDate + " " + nextTime;
In my opinion, it is the most simple solution to the problem, which avoids dabbling with the delimiter pattern. I don't know if it is the best solution, though.