问题描述
// 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”。我能够将其转换为日期格式并打印出来。
但是对于时间字符串,我无法将其打印出来。我遇到以下错误:
但是如果我以相反的方式交换代码的位置,
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);
解决方法
您将日期设置为错误的时间格式。 cal.setTime(timeselected);
的setTime需要Date
Refer java doc
使用与日期相同的格式。