I'm trying to input a string with a mix of characters and have some bit of code remove all but the part that matches the desired SimpleDateFormat
String wholeString = new String("The time is 7:00.");
String timeOnlyString = CODE TO TRIM STRING;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date timeAsObject = sdf.parse(timeOnlyString);
String timeAsString = sdf.format(timeAsObject);
System.out.println(timeAsString);`
With this code I'd like
07:00
Printed in the console.
I recommend that you use java.time, the modern Java date and time API, for your time work.
String wholeString = "The time is 7:00.";
Matcher m = TIME_PATTERN.matcher(wholeString);
while (m.find()) {
String timeOnlyString = m.group();
try {
LocalTime timeAsObject
= LocalTime.parse(timeOnlyString, TIME_FORMATTER);
System.out.println("Time found: " + timeAsObject);
} catch (DateTimeParseException dtpe) {
System.out.println("Looked a bit like a time but couldn’t be parsed as one: " + timeOnlyString);
}
}
I used these two static declarations:
private static final Pattern TIME_PATTERN
= Pattern.compile("\\b\\d{1,2}:\\d{2}\\b");
private static final DateTimeFormatter TIME_FORMATTER
= DateTimeFormatter.ofPattern("H:mm");
Output from my snippet is:
Time found: 07:00
The regular expression that I use for extracting the time from the whole string matches 1 or 2 digits, a colon and 2 digits. It requires a word boundary before and after so we don’t happen to extract a time from 987:12354
or letters1:11moreletters
.
The format pattern string used for the DateTimeFormatter
has just one H
for hour of day. This accepts 1 or 2 digits, so we can parse 15:00
too.
I think that we should take into account that the regex may match more than once in the string, so I am extracting in a loop.
I am parsing in to java.time.LocalTime
. This class is for a time of day (from 00:00 through 23:59:59.999999999), so suits your need much better than the outdated Date
class (which represents neither a date nor a time of day, but a point in time without time zone).