Note that there are some explanatory texts on larger screens.

plurals
  1. POInconsistent ParseExeption with Data Format in Java
    primarykey
    data
    text
    <p>I wrote a simple Util method to convert a <code>String</code> in Java to <code>util.Date</code>. 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:</p> <p>Code:</p> <pre><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"); } } </code></pre> <p>Output:</p> <pre><code>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) </code></pre> <p>Logically, the output should've been <code>Sat Feb 04 13:17:00 CET 2012</code> going by the first output. Why is the <code>ParseException</code> being thrown?</p> <p><strong>EDIT</strong>: The following two lines work correctly:</p> <pre><code>s2d.getDateFromString("02-04-12", "MM-dd-yy"); s2d.getDateFromString("01:17 PM", "hh:mm a"); </code></pre> <p>Output:</p> <pre><code>Sat Feb 04 00:00:00 CET 2012 Thu Jan 01 13:17:00 CET 1970 </code></pre> <p>But the exception happens when I try to parse both date and time together.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload