Home > Software engineering >  How to take date through google voice input in dd/mm/yyyy format?
How to take date through google voice input in dd/mm/yyyy format?

Time:07-09

I want to take the date as a text from the user through google voice input. So when user says:

8 July 2022

Then it will splits that string in dd-mm-yyyy format. How to get it? Should I use any other method to get the date through speech input?

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 100) {
        if (resultCode == RESULT_OK && null != data) {
            ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

            String date = result.get(0);

            date =   date.replace("january", "1");
            date =   date.replace("february", "2");
            date =   date.replace("march", "3");
            date =   date.replace("april", "4");
            date =   date.replace("may", "5");
            date =   date.replace("june", "6");
            date =   date.replace("july", "7");
            date =   date.replace("august", "8");
            date =   date.replace("september", "9");
            date =   date.replace("october", "10");
            date =   date.replace("november", "11");
            date =   date.replace("december", "12");
            String day = date.substring(1, 2);
            String month = date.substring(2, 7);
            String year = date.substring(date.length() - 4);
            String year1 = year.replaceAll("[^A-Za-z]", "");

            mDatebtn.setText(day   "-"   month   "-"   year1);
        }
    }
}

CodePudding user response:

If you can use java.time, you can have the conversion without manipulating Strings.

You will be needing

  • two DateTimeFormatters
    • one that handles the input String and
    • a second one that handles the format of the desired output/result
  • a LocalDate to represent the values of the date to be converted
public static void main(String[] args) {
    // spoken date
    String userWords = "8 July 2022";
    // prepare two DateTimeFormatters, one for parsing the user's words and
    DateTimeFormatter dtfParse = DateTimeFormatter.ofPattern(
                                                    "d MMMM uuuu",
                                                    Locale.ENGLISH);
    // a second one to be used in order to format the desired result
    DateTimeFormatter dtfFormat = DateTimeFormatter.ofPattern(
                                                    "dd-MM-uuuu",
                                                    Locale.ENGLISH);
    // parse the input with the first formatter
    LocalDate localDate = LocalDate.parse(userWords, dtfParse);
    // and print it formatted by the second one
    System.out.println(localDate.format(dtfFormat));
}

Output of this code:

08-07-2022
  • Related