Search code examples
androidsimpledateformat

Could not print time after conversion from string format


 // For Date validation
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
    String datechosen = dateText.getText().toString() ;
    Date dateselected = simpleDateFormat1.parse(datechosen);
    System.out.println(dateselected);


    // For Time validation
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
    String timechosen = timeText.getText().toString();
    Date timeselected = simpleDateFormat.parse(timechosen);
    Calendar cal = Calendar.getInstance();
    cal.setTime(timeselected);
    cal.add(Calendar.HOUR, noofhourselected);
    cal.add(Calendar.MINUTE,  noofminselected);
    timeselected = cal.getTime();
    System.out.println(timeselected);

I am working on converting the string which i have into the date and time format. For example, the string datechosen contain "26/10/2020". I am able to to convert it into date format and print it out.

But for the time string, i am unable to print them out. I am facing the error below:

Screenshot of the log message

But if i swap the position of the codes the other way round,

  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
    String timechosen = timeText.getText().toString();
    Date timeselected = simpleDateFormat.parse(timechosen);
    Calendar cal = Calendar.getInstance();
    cal.setTime(timeselected);
    cal.add(Calendar.HOUR, noofhourselected);
    cal.add(Calendar.MINUTE,  noofminselected);
    timeselected = cal.getTime();
    System.out.println(timeselected);

    // For Date validation
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
    String datechosen = dateText.getText().toString() ;
    Date dateselected = simpleDateFormat1.parse(datechosen);
    System.out.println(dateselected);

The time will be printed instead Screenshot2

Inputfield These are the two input fields


Solution

  • You are setting date in wrong format for time. for cal.setTime(timeselected); setTime takes Date Refer java doc

    Use same format as used for Date.