1 16 package org.joda.time.base; 17 18 import org.joda.time.Duration; 19 import org.joda.time.Period; 20 import org.joda.time.ReadableDuration; 21 import org.joda.time.format.FormatUtils; 22 23 36 public abstract class AbstractDuration implements ReadableDuration { 37 38 41 protected AbstractDuration() { 42 super(); 43 } 44 45 51 public Duration toDuration() { 52 return new Duration(getMillis()); 53 } 54 55 77 public Period toPeriod() { 78 return new Period(getMillis()); 79 } 80 81 90 public int compareTo(Object obj) { 91 ReadableDuration thisDuration = (ReadableDuration) this; 93 ReadableDuration otherDuration = (ReadableDuration) obj; 94 95 long thisMillis = thisDuration.getMillis(); 96 long otherMillis = otherDuration.getMillis(); 97 98 if (thisMillis < otherMillis) { 100 return -1; 101 } 102 if (thisMillis > otherMillis) { 103 return 1; 104 } 105 return 0; 106 } 107 108 114 public boolean isEqual(ReadableDuration duration) { 115 if (duration == null) { 116 duration = Duration.ZERO; 117 } 118 return compareTo(duration) == 0; 119 } 120 121 127 public boolean isLongerThan(ReadableDuration duration) { 128 if (duration == null) { 129 duration = Duration.ZERO; 130 } 131 return compareTo(duration) > 0; 132 } 133 134 140 public boolean isShorterThan(ReadableDuration duration) { 141 if (duration == null) { 142 duration = Duration.ZERO; 143 } 144 return compareTo(duration) < 0; 145 } 146 147 155 public boolean equals(Object duration) { 156 if (this == duration) { 157 return true; 158 } 159 if (duration instanceof ReadableDuration == false) { 160 return false; 161 } 162 ReadableDuration other = (ReadableDuration) duration; 163 return (getMillis() == other.getMillis()); 164 } 165 166 172 public int hashCode() { 173 long len = getMillis(); 174 return (int) (len ^ (len >>> 32)); 175 } 176 177 189 public String toString() { 190 long millis = getMillis(); 191 StringBuffer buf = new StringBuffer (); 192 buf.append("PT"); 193 FormatUtils.appendUnpaddedInteger(buf, millis / 1000); 194 long part = Math.abs(millis % 1000); 195 if (part > 0) { 196 buf.append('.'); 197 FormatUtils.appendPaddedInteger(buf, part, 3); 198 } 199 buf.append('S'); 200 return buf.toString(); 201 } 202 203 } 204 | Popular Tags |