从字符串格式转换后无法打印时间

问题描述

 // 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);

我正在将我拥有的字符串转换为日期和时间格式。例如,字符串datechosen包含“ 26/10/2020”。我能够将其转换为日期格式并打印出来。

但是对于时间字符串,我无法将其打印出来。我遇到以下错误

Screenshot of the log message

但是如果我以相反的方式交换代码的位置,

  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,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);

将改为打印时间

Screenshot2

Inputfield

这是两个输入字段

解决方法

您将日期设置为错误的时间格式。 cal.setTime(timeselected);的setTime需要Date Refer java doc

使用与日期相同的格式。