The format you use in SimpleDateFormat
must match the input String
.
Your input is 2018-01-16T00:07:00.000+05:30
, which is ISO8601 compliant:
- year-month-day (
2018-01-16
)
- followed by the letter
T
- followed by hour:minutes:seconds.milliseconds (
00:07:00.000
)
- followed by the UTC offset (
+05:30
)
Note: the offset +05:30
is not a timezone. Read this to know the difference.
Anyway, the pattern you're using ("yyyy-MM-dd HH:mm:ss z"
) doesn't match the input string:
- it's missing the
T
between date and time
- it's missing the milliseconds
- there's a space before the offset
- the correct letter to parse offsets is
X
(although I think that z
might work, depending on the JVM version you're using; in my tests, it didn't)
So your code should be:
// use "XXX" to parse the whole offset (only one "X" will parse just `+05`, missing the `:30` part)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date d = sdf.parse("2018-01-16T00:07:00.000+05:30");
But it's much better to use the new Java 8 classes, if they're available to you:
// parse ISO8601 compliant string directly
OffsetDateTime odt = OffsetDateTime.parse("2018-01-16T00:07:00.000+05:30");
If you still need to use a java.util.Date
object, it's easy to convert:
// convert to java.util.Date
Date date = Date.from(odt.toInstant());