tl;dr
OffsetDateTime.parse(
"20121116203036Z" ,
DateTimeFormatter.ofPattern( "yyyyMMddHHmmssX" )
).toLocalDateTime()
.toString()
.replace( "T" , " " )
java.time
The java.time classes built into Java make this easy. Avoid the troublesome old date-time classes such as Date
& DateFormat
, now legacy.
String input = "20121116203036Z";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "yyyyMMddHHmmssX" );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2012-11-16T20:30:36Z
To get your output you could define a custom DateTimeFormatter
. A lazier way is to convert to a LocalDateTime
just to lose the Z
on the end, which indicates the offset-from-UTC (Z
is short for Zulu
and means UTC). Then use toString
to generate a string in ISO 8601 format except replace the T
in the middle with a SPACE.
String output = odt.toLocalDateTime().toString().replace( "T" , " " );
2012-11-16 20:30:36
See live code in IdeOne.com.
ISO 8601
I suggest rather than using your format for such date-time values, instead use ISO 8601 standard formats. The usual format for such a value is 2016-11-16T02:45:02Z
. Note the T
in the middle separating year-month-day from hour-minute-second. Alternatively, the standard allows minimizing the use of separators, considered the “basic” version: 20161116T024502Z
but retains the T
in the middle.
The java.time classes can parse and generate the expanded versions but not the basic version.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.