tl;dr
As long as you are using SimpleDateFormat
, there is nothing wrong with your pattern, yyyyMMdd'T'HHmmss'.'SX
.
Just as an aside, you do NOT need to enclose .
within (single) quotes i.e. you can simply use yyyyMMdd'T'HHmmss.SX
.
What's the problem then?
The problem is that you are passing the pattern, instead of the date-time string, to SimpleDateFormat#parse
. Using your pattern, the following code runs successfully:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'.'SX");
Date date = formatter.parse("20150724T104139.118+02");
// ...
}
}
More evidence to prove that there is nothing wrong with your pattern to be used with SimpleDateFormat
for parsing:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'.'SX");
Date date = formatter.parse("20150724T104139.118+02");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'.'SSSX");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+02"));
System.out.println(sdf.format(date));
}
}
Output:
20150724T104139.118+02
java.time
Note that the legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Demo 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) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss.SSSX", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("20150724T104139.118+02", dtf);
System.out.println(odt);
}
}
Output:
2015-07-24T10:41:39.118+02:00
In case you need an object of java.util.Date
from this object of OffsetDateTime
, you can do so as follows:
Date date = Date.from(odt.toInstant());
Learn more about the 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.