4 Replies Latest reply on Feb 12, 2007 9:07 PM by dadams07

    SimpleDateFormat does not handle leading blanks for HHmmss format

    807606
      Hi,

      I came accross a piece of code :


      import java.util.*;
      import java.io.*;
      import java.text.*;

      public class SDFTest{
      public static void main(String[] args) {
      try{
      System.out.println("\"102030\" --> " + getTime("102030"));
      System.out.println("\"002030\" --> " + getTime("002030"));
      System.out.println("\" 12030\" --> " + getTime(" 12030"));
      System.out.println("\" 2030\" --> " + getTime(" 2030"));
      System.out.println("\" \" --> " + getTime(" "));
      }catch(Exception e){
      e.printStackTrace();
      }
      }

      private static String getTime(String time_str){
      SimpleDateFormat sdf = new SimpleDateFormat("HHmmss", new Locale("ja", ""));
      ParsePosition pp = new ParsePosition(0);
      sdf.setLenient(false);
      Date date = sdf.parse(time_str, pp);
      return sdf.format(date);
      }
      }

      The output from this code using java 1.4 is as follows

      "102030" --> 102030
      "002030" --> 002030
      " 12030" --> 012030
      java.lang.NullPointerException
      at java.util.Calendar.setTime(Calendar.java:1032)
      at java.text.SimpleDateFormat.format(SimpleDateFormat.java:785)
      at java.text.SimpleDateFormat.format(SimpleDateFormat.java:778)
      at java.text.DateFormat.format(DateFormat.java:314)
      at testSimpleDateFormat.getTime(testSimpleDateFormat.java:23)
      at testSimpleDateFormat.main(testSimpleDateFormat.java:11)

      So, with a string like " 2030", I get a null pointer exception. Is the string format incorrect for the pattern "HHmmss" ?