java - Parse date in String format to Gregorian Calendar, with hour and minute -


i'm trying parse input string date 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 keeps giving error:

java.util.inputmismatchexception    @ java.util.scanner.throwfor(unknown source)    @ java.util.scanner.next(unknown source)    @ java.util.scanner.next(unknown source) 

can me? works if don't specify hours , minutes not this...

looking @ source code of scanner.next(pattern), called scanner.next(string), method roughly follows these steps:

  1. use delimiter pattern skips delimiters current position in stream.

  2. search next delimiter in stream. blocks if more input needed find delimiter. continue if end of stream

  3. check pattern matches token between current position , next delimiter (or end of stream).

  4. return token if matches. otherwise, throw exception.

since space matched default delimiter pattern ("\\p{javawhitespace}+"), scanner tokenizes @ date part , tries match token against pattern , fails.

01.01.2014 00:00 ^--------^^   token   |           |       delimiter 

one way 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 opinion, simple solution problem, avoids dabbling delimiter pattern. don't know if best solution, though.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -