0

I am getting a null returned by SimpleDateFormat. But I feel I have done everything correctly.

Below is my code snippet

format = new SimpleDateFormat("yyyy-dd-MM'T'H:mm:ss'Z'", Locale.US);
format.setLenient(true);
ParsePosition pos = new ParsePosition(0);

String timeStr = "2013-10-05T01:21:07Z";
System.out.println(format.format(new Date()));
System.out.println(timeStr);

Date d = format.parse(timeStr,pos);
d.getTime();

Gives the output

2014-30-05T13:43:05Z
2013-10-05T01:21:07Z
Exception in thread "main" java.lang.NullPointerException

I have tried a couple of options mentioned in other posts in this forum. But I am still getting the error. Am I overlooking something trivial?

promaxdev
  • 455
  • 1
  • 6
  • 19

1 Answers1

0

Although you might think now all is okay with your code according to the comments above, I would say, nothing is okay.

  1. Have a look again at your pattern. Probably you want an ISO-8601-compatible pattern. This is slightly different however: "yyyy-MM-dd'T'HH:mm:ssXXX" (for Java 7) You seem to have changed the position of month and day!

  2. Z is not just a literal in ISO-strings. It stands for timezone UTC (Zulu time), but you parse the string with your system timezone (because you have not explicitly set a timezone on your format object) which can be quite different. The right solution is to use the pattern symbol X introduced in Java 7. If you still use an older Java version then you can escape the Z (as you have done it) but MUST set the timezone of your format object to "GMT". Otherwise you get wrong results without exception.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126