I need to parse a String
into dd/MM/YY hh:mm:ss
format.
Suppose if a String
has value 09/06/17 05:59:59
then it should be parsed but if a String
has value 09/06/2017 05:59:59
then this is also a valid format and getting parsed but in my requirement, a parse exception should be thrown for the later.
Code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
String line=" 09/06/17 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";
//String line=" 09/06/2017 05:59:59 20170609IT36701706080107 42 103 Output USD 970.20 IT3670";
String dt=null;
dt=line.substring(1, 19);
SimpleDateFormat org_format = new SimpleDateFormat("dd/MM/YY hh:mm:ss");
SimpleDateFormat tgt_format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
dt=line.substring(1, 19);
System.out.println(dt);
Date date = org_format.parse(dt);
System.out.println(date);
String tgt_date=tgt_format.format(date);
System.out.println(tgt_date);
} catch (ParseException e) {
System.out.println(line);
}
}
}
Problem - In the code, uncommented line variable and commented line variable, both are giving result successfully. but the commented line should throw parsable exception as it's the pattern dd/MM/yyyy
, not dd/MM/yy
.
fmt.setLenient(false)
is not working.
I'm using Java 7. Don't have option to use Java 8 or later so can't use java.time
.