Regex is not the right tool for your requirement
As also suggested by anubhava and Basil Bourque, the best tool to use here is date-time API.
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String[] args) {
String strDateTime = "Thu Dec 22 01:12:22 UTC 2022";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss VV uuuu", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, parser);
LocalTime time = zdt.toLocalTime();
System.out.println(time);
// Or get the string representation
String strTime = time.toString();
System.out.println(strTime);
}
}
Output:
01:12:22
01:12:22
An important piece of advice from Ole V.V.: If the time substring has zero seconds e.g. 01:12:00
, the default implementation of LocalTime#toString
removes the trailing :00
. In that, you will need a formatter also to format the time.
class Main {
public static void main(String[] args) {
String strDateTime = "Thu Dec 22 01:12:00 UTC 2022";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss VV uuuu", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, parser);
LocalTime time = zdt.toLocalTime();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.ENGLISH);
String strTime = time.format(formatter);
System.out.println(strTime);
}
}
Output:
01:12:00
Learn more about the modern Date-Time API from Trail: Date Time.