While validating the given string text is of Hmm format getting this error
java.text.ParseException: Unparseable date: "1637"
but this is working for text "747".
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Validation{
public void validateDateFormat(String format,String text){
SimpleDateFormat sdfrmt = new SimpleDateFormat(format);
sdfrmt.setLenient(false);
Date testDate = null;
try {
testDate = sdfrmt.parse(text);
} catch (ParseException e) {
System.out.println("dateFormat Exception :");
e.printStackTrace();
}
}
public static void main(String []args){
Validation val = new Validation();
val.validateDateFormat("Hmm","747"); //working
val.validateDateFormat("Hmm","1637");//not working
}
}
This is for validating the given columns from the uploaded file.So wrote this to be dynamic based on the format written in the config for each column.
Well, it should work.
But you should use the newer Java Date and Time API (JSR 310) available in the java.time
package.
If you then replace Date
with LocalTime
, SimpleDateFormat
with DateTimeFormatter
(using the ofPattern
factory method) and ParseException
with DateTimeParseException
, it'll work .
This is happening because the SimpleDateFormat
is unable to parse the given date using the format you have given.
Let's understand - your format is Hmm
and you have given the date as 747
then, of course during parsing, the first letter 7
of the date is mapped to the first letter "H" of the format ie hours and 47
is mapped to mm
ie minutes and hence it is able to convert correctly but for the next date 1637
it is failing because it does not know which letter to assign to H
.
Here are some options you can try to make it more generic, choose format such as HHmm
and always give the date of length 4, for eg for 747
enter the input as 0747
and it should work.
Or choose a format that is more clear for the parser to map for eg you can choose the format as H:mm
and give the inputs as 7:47
or 16:37
since there is a delimiter :
between hours and minutes, the parser will be able to parse all types of time irrespective of the length of the given input 3 or 4.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.