Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Date format year format issue

I am getting issues with Date Format. I am using SimpleDateFormat to parse date and using MM/dd/yyyy format to parse date, its working properly with correct input like 11/11/2011 and its returning correct result (Fri Nov 11 00:00:00 IST 2011)

But if we enter 11/11/11 as input then its not working properly (Wed Nov 11 00:00:00 IST 11), nor giving parse error.

public static void main(String[] args) {
    String format = "MM/dd/yyyy";
    String dt = "11/11/11";
    Date date = null;
    try {
        date = TestDate.parDate(dt, format);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(date);

}

public static Date parDate(String value, String dateFormat) throws ParseException {
    Date date = null;
    date = new SimpleDateFormat(dateFormat).parse(value);
    return date;
}
like image 546
Kuldeep Avatar asked Dec 17 '25 20:12

Kuldeep


2 Answers

If you can use Java 8 or above, use DateTimeFormatter and LocalDate classes to parse date values. It will throw an error if the input is not in the expected format.

DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
LocalDate date1 = LocalDate.parse("11-11-2011", formatter1);
System.out.println(date1);

Above will work as expected but if you try to parse "11-11-11" with the same formatter object you will get an exception like

Exception in thread "main" java.time.format.DateTimeParseException: Text '11-11-11' could not be parsed at index 6
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)
at com.is.TestDate.main(TestDate.java:14)
like image 170
maneesh Avatar answered Dec 19 '25 12:12

maneesh


Use MM/dd/yy for both 11/11/11 and 11/11/2011.

like image 34
zhh Avatar answered Dec 19 '25 12:12

zhh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!