Use org.apache.commons.lang3.StringUtils
conviniene methods for string parsing. Also change Calendar
to java.time.LocalDate
. Here is a working example:
Rule.java
import java.time.LocalDate;
import java.util.StringJoiner;
public class Rule {
private String role;
private LocalDate dateFrom;
private LocalDate dateTo;
public Rule(final String role, final LocalDate dateFrom, final LocalDate dateTo) {
this.role = role;
this.dateFrom = dateFrom;
this.dateTo = dateTo;
}
@Override
public String toString() {
return new StringJoiner(", ", Rule.class.getSimpleName() + "[", "]")
.add("role='" + role + "'")
.add("dateFrom=" + dateFrom)
.add("dateTo=" + dateTo)
.toString();
}
}
Main.java
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String mine = "Role = Student; DateFrom = 21/12/2020; DateTo = 10/01/2021;";
String role = StringUtils.substringBetween(mine, "Role =", ";").trim();
String dateFrom = StringUtils.substringBetween(mine, "DateFrom =", ";").trim();
String dateTo = StringUtils.substringBetween(mine, "DateTo =", ";").trim();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
LocalDate localDateFrom = LocalDate.parse(dateFrom, formatter);
LocalDate localDateTo = LocalDate.parse(dateTo, formatter);
Rule rule = new Rule(role, localDateFrom, localDateFrom);
System.out.println(rule);
}
}
Output (You can format the date as per your preference)
Rule[role='Student', dateFrom=2020-12-21, dateTo=2020-12-21]