The answer by deHaar is correct. This answer shows an easier way of solving this problem.
You can use the regex, (\.)(\d{1,2}:\d{1,2})
to replace the .
(group#1 in the regex) before the timezone offset part (group#2 in the regex) with a +
.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2021010112:12:12.10:00";
strDateTime = strDateTime.replaceFirst("(\\.)(\\d{1,2}:\\d{1,2})", "+$2");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHH:mm:ssXXX", Locale.ENGLISH);
Instant instant = OffsetDateTime.parse(strDateTime, dtf).toInstant();
System.out.println(instant);
}
}
Output:
2021-01-01T02:12:12Z
ONLINE DEMO
Alternatively, you can use the regex, \.(\d{1,2}:\d{1,2})
and prepend group#1 with a +
sign. Note that the DateTimeFormatter
needs to be adjusted accordingly.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2021010112:12:12.10:00";
strDateTime = strDateTime.replaceFirst("\\.(\\d{1,2}:\\d{1,2})", ".+$1");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMddHH:mm:ss.XXX", Locale.ENGLISH);
Instant instant = OffsetDateTime.parse(strDateTime, dtf).toInstant();
System.out.println(instant);
}
}
ONLINE DEMO
The benefits of using this alternative solution is as described in the following comment by Ole V.V.:
Just speculating, maybe a minus sign would be present in case of a
negative UTC offset. If so, maybe use
strDateTime.replaceFirst("\\.(\\d{1,2}:\\d{1,2})", ".+$1")
to obtain
2021010112:12:12.+10:00 in the positive offset case, after which both
positive and negative offset (and zero) could be parsed.