java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API: Your input string has timezone offset and therefore it should be parsed to OffsetDateTime
.
Demo:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssxx", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("2013-03-13T20:59:31+0000", dtf);
System.out.println(odt);
}
}
Output:
2013-03-13T20:59:31Z
ONLINE DEMO
The Z
in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC
timezone (which has the timezone offset of +00:00
hours).
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time
API with JDBC.
If at all you need java.util.Date
:
You can use Date#from
to get an instance of java.util.Date
, as shown below:
Date date = Date.from(odt.toInstant());
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time
.