I want to change the date format from 20230523154325 to 2023-05-23T15:43:25+0000
You can do that with java.time
if you are using Java 8 or higher.
Example Code
public static void main(String[] args) {
// example input
String oldDate = "20230523154325";
// prepare a parser
DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
// parse the oldDate with the parser
LocalDateTime ldt = LocalDateTime.parse(oldDate, parser);
// print the result (NO OFFSET SO FAR!!!)
System.out.println(ldt);
// add an offset (UTC = +00:00 = Z)
OffsetDateTime odt = ldt.atOffset(ZoneOffset.UTC);
// print it
System.out.println(odt);
// prepare a formatter for the desired output
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssxxxx");
// then print the datetime plus offset in the desired format
System.out.println(odt.format(formatter));
}
Output
2023-05-23T15:43:25
2023-05-23T15:43:25Z
2023-05-23T15:43:25+0000
There are prebuilt ones for standard/common formats like DateTimeFormatter.ISO_OFFSET_DATE_TIME
, which are worth a look. However, you have to create those two DateTimeFormatter
s manually in this case, because none of the prebuilt ones can parse your input format and none of them can produce your desired output.
Why did your attempt fail to produce the desired result?
Your attempt involves the zone/offset of your machine/jvm, which will even change the offset when the code is executed on another machine with a different zone/offset.
That's why you
- should stop using
java.util.Date
and java.text.SimpleDateFormat
whenever/wherever you can…
- should switch to
java.time
because you have full control over zone/offset handling
Compact / Short Version
public static void main(String[] args) {
String oldDate = "20230523154325";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("uuuu-MM-dd'T'HH:mm:ssxxxx");
String desiredResult = LocalDateTime.parse(oldDate, parser)
.atOffset(ZoneOffset.UTC)
.format(formatter);
System.out.println(desiredResult);
}
Output
2023-05-23T15:43:25+0000