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* .
Using modern date-time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "Thu Dec 17 15:37:43 GMT+05:30 2015";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("E MMM d H:m:s O u", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtfInput);
// Default string i.e. OffsetDateTime#toString
System.out.println(odt);
// A custom string
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssO", Locale.ENGLISH);
String formatted = odt.format(dtfOutput);
System.out.println(formatted);
}
}
Output:
2015-12-17T15:37:43+05:30
2015-12-17T15:37:43GMT+5:30
Learn more about the modern date-time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. 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 and How to use ThreeTenABP in Android Project.