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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With