Java 8 introduced a variety of date functions and when it comes to parsing an formatting a great article can be found here. One class that was introduced was the DateTimeFormatter which has one big upside compared to e.g. SimpleDateFormatter
- DateTimeFormatter it is thread-safe.
So, I would probably not use the substring
-approach that was mentioned in an answer. Instead I would use the DateTimeFormatter
to parse the string and then output it in the required format. This also offers some validation that the input format is as expected and that the output format is valid as well.
Example:
@Test
public void test() throws IOException, ParseException {
// Setup the input formatter
final DateTimeFormatter inputFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
// Parse and validate the date
final LocalDateTime parsed =
LocalDateTime.parse("2015-01-06T06:36:12Z", inputFormatter);
// Setup the output formatter
final DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
// Format the date to the desired format
String formatted = outputFormatter.format(parsed);
// Verify the contents (part of test only)
Assert.assertEquals("06:36:12", formatted);
}
The new date and time features in Java 8 are heavily inspired by Joda-Time and this SO-question is good reading for those who are curious what the differences are.