I know the pattern should be match like
yyyy-MM-ddTHH:mm:ss.s
No, there are two problems in this pattern:
- The symbol for fraction-of-second is
S
, but you have used s
.
- The
ZoneOffset
specifier, Z
is missing in the pattern.
java.time
The accepted answer uses SimpleDateFormat
which was the correct thing to do in 2012. In Mar 2014, the java.util
date-time API and their formatting API, SimpleDateFormat
were supplanted by the modern Date-Time API. Since then, it is highly recommended to stop using the legacy date-time API.
Demo using the modern date-time API:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH);
System.out.println(OffsetDateTime.now(ZoneOffset.of("-06:00")).format(dtf));
}
}
Output:
2022-12-28T13:21:05.459-0600
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.