Skip to content

Commit

Permalink
Simplify period formatting and implement serializable
Browse files Browse the repository at this point in the history
  • Loading branch information
benfortuna committed Apr 30, 2019
1 parent 7ac4bd1 commit f3ba980
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 18 deletions.
33 changes: 15 additions & 18 deletions src/main/java/net/fortuna/ical4j/model/TemporalAmountAdapter.java
Expand Up @@ -3,6 +3,7 @@
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.io.Serializable;
import java.time.Duration;
import java.time.Instant;
import java.time.Period;
Expand All @@ -12,7 +13,7 @@
/**
* Support adapter for {@link java.time.temporal.TemporalAmount} representation in iCalendar format.
*/
public class TemporalAmountAdapter {
public class TemporalAmountAdapter implements Serializable {

private final TemporalAmount duration;

Expand Down Expand Up @@ -46,28 +47,24 @@ public String toString() {
*/
private String periodToString(Period period) {
String retVal;
if (period.getYears() > 0) {
int weeks = Math.abs(period.getYears()) * 52;
if (period.getYears() < 0) {
weeks = -weeks;
}
Period absPeriod = period.isNegative() ? period.negated() : period;
if (absPeriod.getYears() != 0) {
int weeks = absPeriod.getYears() * 52;
retVal = String.format("P%dW", weeks);
} else if (period.getMonths() > 0) {
int weeks = Math.abs(period.getMonths()) * 4;
if (period.getMonths() < 0) {
weeks = -weeks;
}
} else if (absPeriod.getMonths() != 0) {
int weeks = absPeriod.getMonths() * 4;
retVal = String.format("P%dW", weeks);
} else if (period.getDays() % 7 == 0) {
int weeks = Math.abs(period.getDays()) / 7;
if (period.getDays() < 0) {
weeks = -weeks;
}
} else if (absPeriod.getDays() % 7 == 0) {
int weeks = absPeriod.getDays() / 7;
retVal = String.format("P%dW", weeks);
} else {
retVal = period.toString();
retVal = absPeriod.toString();
}
if (period.isNegative()) {
return "-" + retVal;
} else {
return retVal;
}
return retVal;
}

/**
Expand Down
Expand Up @@ -22,6 +22,7 @@ class TemporalAmountAdapterTest extends Specification {
java.time.Period.ofDays(364) | "P52W"
java.time.Period.ofYears(1) | "P52W"
java.time.Period.ofMonths(6) | "P24W"
java.time.Period.ofMonths(-6) | "-P24W"
Duration.ofDays(15).plusHours(5).plusSeconds(20) | 'P15DT5H0M20S'
}

Expand Down

0 comments on commit f3ba980

Please sign in to comment.