Skip to content

Instantly share code, notes, and snippets.

@sirk390
Created September 2, 2023 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirk390/40678d8fbe5c0108f663dbe2cd1e1fba to your computer and use it in GitHub Desktop.
Save sirk390/40678d8fbe5c0108f663dbe2cd1e1fba to your computer and use it in GitHub Desktop.
extractDates.java
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.time.LocalDate;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.time.DateTimeException;
public class MyClass {
public static void main(String args[]) {
List<LocalDate> dates = extractDates("auhz uazhd a29-02-2023zz r29-02-2024z 8-02-2024");
System.out.println(dates);
int uniqueYears = countUniqueYears("auhz uazhd a29-02-2023zz r29-02-2024z 8-02-2024");
System.out.println(uniqueYears);
}
public static int countUniqueYears(String inputStr) {
List<LocalDate> dates = extractDates(inputStr);
Set uniqueDates = new HashSet<Integer>();
dates.forEach((d) -> uniqueDates.add(d.getYear()));
return uniqueDates.size();
}
public static List<LocalDate> extractDates(String inputStr) {
List<LocalDate> result = new ArrayList<LocalDate>();
Pattern pattern = Pattern.compile("(\\d{1,2})-(\\d{1,2})-(\\d{2,4})");
Matcher matcher = pattern.matcher(inputStr);
while (matcher.find()) {
String day = matcher.group(1);
String month = matcher.group(2);
String year = matcher.group(3);
try {
result.add(LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day)));
}
catch (DateTimeException exception) {
// ignore bad dates
}
}
return result;
}
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment