-
-
Save sirk390/b2a703737a3321bcaf3585854354dbe2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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