I have a String that looks something like this: “n YEARS n MONTHS n WEEKS n DAYS” (note that the constants may or may not be pluralized)
I need to convert this to either a Joda Period object or an ISO 8601 formatted String (which can in turn be converted to a Period object).
Does anyone have any code, or can they point me to a library to do this?
Update: In case anyone needs to do this, here is the working code. Unfortunately, I had to dynamically build the PeriodFormatterBuilder since the fields were optional. A bit ugly, but it works.
Update2: Fixed error pointed out in comments.
String text = expr1a.getText();
System.out.println(text);
PeriodFormatterBuilder pfb = new PeriodFormatterBuilder().printZeroAlways();
int yearIndex = text.indexOf("YEAR");
int monthIndex = text.indexOf("MONTH");
int weekIndex = text.indexOf("WEEK");
int dayIndex = text.indexOf("DAY");
if (yearIndex > -1) {
pfb = pfb.appendYears().appendSuffix(" YEAR"," YEARS");
}
if (monthIndex > -1) {
if (yearIndex > -1) {
pfb = pfb.appendPrefix(" ").appendMonths().appendSuffix(" MONTH", " MONTHS");
} else {
pfb = pfb.appendMonths().appendSuffix(" MONTH", " MONTHS");
}
}
if (weekIndex > -1) {
if (yearIndex > -1 || monthIndex > -1) {
pfb = pfb.appendPrefix(" ").appendWeeks().appendSuffix(" WEEK", " WEEKS");
} else {
pfb = pfb.appendWeeks().appendSuffix(" WEEK", " WEEKS");
}
}
if (dayIndex > -1) {
if (yearIndex > -1 || monthIndex > -1 || weekIndex > -1) {
pfb = pfb.appendPrefix(" ").appendDays().appendSuffix(" DAY"," DAYS");
} else {
pfb = pfb.appendDays().appendSuffix(" DAY"," DAYS");
}
}
PeriodFormatter pf = pfb.toFormatter();
Period period = Period.parse(text, pf);
return period;
You can use the PeriodFormatterBuilder of the joda time API to construct an instance, which parses your format. There is also handling for plurals of the constants.