Parsing string, date and time from a user defined sentence.

  • Replies:2
  • OpenNot stickiedUnanswered
  • Forum posts: 8

Feb 9, 2016 7:53:47 AM via Website

I want to parse string, date and time from a user defined sentence. For eg. In a sentence " Project review meeting is on October 6th 2016 at 9.00 am." String: Project review meeting, Date: 2016/10/06, time 09.00 a.m. should be separated. Please suggest me how to do this?

Thanks in advance.

I have tried with the below code.

             SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); 
                 try {  
                 date = format.parse(edittext.getText().toString());  

             } catch (ParseException e) {  
                 // TODO Auto-generated catch block  

                 datetext.setText("" +date);  

— modified on Feb 9, 2016 10:27:51 AM

  • Forum posts: 12

Feb 13, 2016 3:47:16 AM via Website

In your example above you would need to iterate over the input string as follows:

final String test = "Project review meeting is on 2/12/16 7:30 PM.";
final SimpleDateFormat format = new SimpleDateFormat();
final ParsePosition position = new ParsePosition(0);
Date date = null;

int index = 0;
final int length = test.length();
for (index=0; index < length && date == null; index++) {
    date = format.parse(test, position);

if (date != null) {
    Log.v(TAG, "date " + date + " at " + index + " length " + (position.getIndex() - index));
} else {
    Log.v(TAG, "date not found");

Note that the pattern you provided the constructor of SimpleDateFormat did not match the provided sample string; I altered the above to use a default date string. The above probably won't satisfy your requirements; you'll probably need to look for a much more advanced date parser if you want to allow for anything more than trivial variations to the accepted date format as well as another package to trim connecting text in your example above (-"is on") - good luck!