Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent ParseExeption with Data Format in Java

Tags:

java

I wrote a simple Util method to convert a String in Java to util.Date. What I am not able to figure out is why the method works for the first input, and fails for the second one, given that the inputs are identical:

Code:

package util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDate {

    public Date getDateFromString(String strDate, String dateFormat) {

        DateFormat df = new SimpleDateFormat(dateFormat);
        Date date = null;

        try {

            date = df.parse(strDate);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println(date);

        return date;
    }

    public static void main(String[] args)  {

        StringToDate s2d = new StringToDate();

        s2d.getDateFromString("12-18-11, 10:36 AM","MM-dd-yy, hh:mm a");
        s2d.getDateFromString("02-04-12, 01:17 PM","MM-dd-yy, hh:mm a");
    }
}

Output:

Sun Dec 18 10:36:00 CET 2011
null
java.text.ParseException: Unparseable date: "02-04-12, 01:17 PM"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at util.StringToDate.getDateFromString(StringToDate.java:17)
    at util.StringToDate.main(StringToDate.java:33)

Logically, the output should've been Sat Feb 04 13:17:00 CET 2012 going by the first output. Why is the ParseException being thrown?

EDIT: The following two lines work correctly:

s2d.getDateFromString("02-04-12", "MM-dd-yy");
s2d.getDateFromString("01:17 PM", "hh:mm a");

Output:

Sat Feb 04 00:00:00 CET 2012
Thu Jan 01 13:17:00 CET 1970

But the exception happens when I try to parse both date and time together.

like image 494
SNag Avatar asked Apr 01 '12 14:04

SNag


1 Answers

Do you have a non-breaking space, or some other Unicode space character, somewhere in either your date string or format mask?

I was able to reproduce your error if I replaced one of the spaces in the second of your date strings with a non-breaking space, such as Unicode character 160.

like image 89
Luke Woodward Avatar answered Nov 10 '22 02:11

Luke Woodward