001: /*
002: * Copyright 2001-2006 Stephen Colebourne
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016: package org.joda.time;
017:
018: import org.joda.time.base.BaseSingleFieldPeriod;
019: import org.joda.time.field.FieldUtils;
020: import org.joda.time.format.ISOPeriodFormat;
021: import org.joda.time.format.PeriodFormatter;
022:
023: /**
024: * An immutable time period representing a number of hours.
025: * <p>
026: * <code>Hours</code> is an immutable period that can only store hours.
027: * It does not store years, months or minutes for example. As such it is a
028: * type-safe way of representing a number of hours in an application.
029: * <p>
030: * The number of hours is set in the constructor, and may be queried using
031: * <code>getHours()</code>. Basic mathematical operations are provided -
032: * <code>plus()</code>, <code>minus()</code>, <code>multipliedBy()</code> and
033: * <code>dividedBy()</code>.
034: * <p>
035: * <code>Hours</code> is thread-safe and immutable.
036: *
037: * @author Stephen Colebourne
038: * @since 1.4
039: */
040: public final class Hours extends BaseSingleFieldPeriod {
041:
042: /** Constant representing zero hours. */
043: public static final Hours ZERO = new Hours(0);
044: /** Constant representing one hour. */
045: public static final Hours ONE = new Hours(1);
046: /** Constant representing two hours. */
047: public static final Hours TWO = new Hours(2);
048: /** Constant representing three hours. */
049: public static final Hours THREE = new Hours(3);
050: /** Constant representing four hours. */
051: public static final Hours FOUR = new Hours(4);
052: /** Constant representing five hours. */
053: public static final Hours FIVE = new Hours(5);
054: /** Constant representing six hours. */
055: public static final Hours SIX = new Hours(6);
056: /** Constant representing seven hours. */
057: public static final Hours SEVEN = new Hours(7);
058: /** Constant representing eight hours. */
059: public static final Hours EIGHT = new Hours(8);
060: /** Constant representing the maximum number of hours that can be stored in this object. */
061: public static final Hours MAX_VALUE = new Hours(Integer.MAX_VALUE);
062: /** Constant representing the minimum number of hours that can be stored in this object. */
063: public static final Hours MIN_VALUE = new Hours(Integer.MIN_VALUE);
064:
065: /** The paser to use for this class. */
066: private static final PeriodFormatter PARSER = ISOPeriodFormat
067: .standard().withParseType(PeriodType.hours());
068: /** Serialization version. */
069: private static final long serialVersionUID = 87525275727380864L;
070:
071: //-----------------------------------------------------------------------
072: /**
073: * Obtains an instance of <code>Hours</code> that may be cached.
074: * <code>Hours</code> is immutable, so instances can be cached and shared.
075: * This factory method provides access to shared instances.
076: *
077: * @param hours the number of hours to obtain an instance for
078: * @return the instance of Hours
079: */
080: public static Hours hours(int hours) {
081: switch (hours) {
082: case 0:
083: return ZERO;
084: case 1:
085: return ONE;
086: case 2:
087: return TWO;
088: case 3:
089: return THREE;
090: case 4:
091: return FOUR;
092: case 5:
093: return FIVE;
094: case 6:
095: return SIX;
096: case 7:
097: return SEVEN;
098: case 8:
099: return EIGHT;
100: case Integer.MAX_VALUE:
101: return MAX_VALUE;
102: case Integer.MIN_VALUE:
103: return MIN_VALUE;
104: default:
105: return new Hours(hours);
106: }
107: }
108:
109: //-----------------------------------------------------------------------
110: /**
111: * Creates a <code>Hours</code> representing the number of whole hours
112: * between the two specified datetimes.
113: *
114: * @param start the start instant, must not be null
115: * @param end the end instant, must not be null
116: * @return the period in hours
117: * @throws IllegalArgumentException if the instants are null or invalid
118: */
119: public static Hours hoursBetween(ReadableInstant start,
120: ReadableInstant end) {
121: int amount = BaseSingleFieldPeriod.between(start, end,
122: DurationFieldType.hours());
123: return Hours.hours(amount);
124: }
125:
126: /**
127: * Creates a <code>Hours</code> representing the number of whole hours
128: * between the two specified partial datetimes.
129: * <p>
130: * The two partials must contain the same fields, for example you can specify
131: * two <code>LocalTime</code> objects.
132: *
133: * @param start the start partial date, must not be null
134: * @param end the end partial date, must not be null
135: * @return the period in hours
136: * @throws IllegalArgumentException if the partials are null or invalid
137: */
138: public static Hours hoursBetween(ReadablePartial start,
139: ReadablePartial end) {
140: if (start instanceof LocalTime && end instanceof LocalTime) {
141: Chronology chrono = DateTimeUtils.getChronology(start
142: .getChronology());
143: int hours = chrono.hours().getDifference(
144: ((LocalTime) end).getLocalMillis(),
145: ((LocalTime) start).getLocalMillis());
146: return Hours.hours(hours);
147: }
148: int amount = BaseSingleFieldPeriod.between(start, end, ZERO);
149: return Hours.hours(amount);
150: }
151:
152: /**
153: * Creates a <code>Hours</code> representing the number of whole hours
154: * in the specified interval.
155: *
156: * @param interval the interval to extract hours from, null returns zero
157: * @return the period in hours
158: * @throws IllegalArgumentException if the partials are null or invalid
159: */
160: public static Hours hoursIn(ReadableInterval interval) {
161: if (interval == null) {
162: return Hours.ZERO;
163: }
164: int amount = BaseSingleFieldPeriod.between(interval.getStart(),
165: interval.getEnd(), DurationFieldType.hours());
166: return Hours.hours(amount);
167: }
168:
169: /**
170: * Creates a new <code>Hours</code> representing the number of complete
171: * standard length hours in the specified period.
172: * <p>
173: * This factory method converts all fields from the period to hours using standardised
174: * durations for each field. Only those fields which have a precise duration in
175: * the ISO UTC chronology can be converted.
176: * <ul>
177: * <li>One week consists of 7 days.
178: * <li>One day consists of 24 hours.
179: * <li>One hour consists of 60 minutes.
180: * <li>One minute consists of 60 seconds.
181: * <li>One second consists of 1000 milliseconds.
182: * </ul>
183: * Months and Years are imprecise and periods containing these values cannot be converted.
184: *
185: * @param period the period to get the number of hours from, null returns zero
186: * @return the period in hours
187: * @throws IllegalArgumentException if the period contains imprecise duration values
188: */
189: public static Hours standardHoursIn(ReadablePeriod period) {
190: int amount = BaseSingleFieldPeriod.standardPeriodIn(period,
191: DateTimeConstants.MILLIS_PER_HOUR);
192: return Hours.hours(amount);
193: }
194:
195: /**
196: * Creates a new <code>Hours</code> by parsing a string in the ISO8601 format 'PTnH'.
197: * <p>
198: * The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the
199: * hours component may be non-zero. If any other component is non-zero, an exception
200: * will be thrown.
201: *
202: * @param periodStr the period string, null returns zero
203: * @return the period in hours
204: * @throws IllegalArgumentException if the string format is invalid
205: */
206: public static Hours parseHours(String periodStr) {
207: if (periodStr == null) {
208: return Hours.ZERO;
209: }
210: Period p = PARSER.parsePeriod(periodStr);
211: return Hours.hours(p.getHours());
212: }
213:
214: //-----------------------------------------------------------------------
215: /**
216: * Creates a new instance representing a number of hours.
217: * You should consider using the factory method {@link #hours(int)}
218: * instead of the constructor.
219: *
220: * @param hours the number of hours to represent
221: */
222: private Hours(int hours) {
223: super (hours);
224: }
225:
226: /**
227: * Resolves singletons.
228: *
229: * @return the singleton instance
230: */
231: private Object readResolve() {
232: return Hours.hours(getValue());
233: }
234:
235: //-----------------------------------------------------------------------
236: /**
237: * Gets the duration field type, which is <code>hours</code>.
238: *
239: * @return the period type
240: */
241: public DurationFieldType getFieldType() {
242: return DurationFieldType.hours();
243: }
244:
245: /**
246: * Gets the period type, which is <code>hours</code>.
247: *
248: * @return the period type
249: */
250: public PeriodType getPeriodType() {
251: return PeriodType.hours();
252: }
253:
254: //-----------------------------------------------------------------------
255: /**
256: * Converts this period in hours to a period in weeks assuming a
257: * 7 day week and 24 hour day.
258: * <p>
259: * This method allows you to convert between different types of period.
260: * However to achieve this it makes the assumption that all weeks are 7 days
261: * long and all days are 24 hours long.
262: * This is not true when daylight savings time is considered, and may also
263: * not be true for some unusual chronologies. However, it is included as it
264: * is a useful operation for many applications and business rules.
265: *
266: * @return a period representing the number of whole weeks for this number of hours
267: */
268: public Weeks toStandardWeeks() {
269: return Weeks.weeks(getValue()
270: / DateTimeConstants.HOURS_PER_WEEK);
271: }
272:
273: /**
274: * Converts this period in hours to a period in days assuming a
275: * 24 hour day.
276: * <p>
277: * This method allows you to convert between different types of period.
278: * However to achieve this it makes the assumption that all days are 24 hours long.
279: * This is not true when daylight savings time is considered, and may also
280: * not be true for some unusual chronologies. However, it is included as it
281: * is a useful operation for many applications and business rules.
282: *
283: * @return a period representing the number of whole days for this number of hours
284: */
285: public Days toStandardDays() {
286: return Days.days(getValue() / DateTimeConstants.HOURS_PER_DAY);
287: }
288:
289: /**
290: * Converts this period in hours to a period in minutes assuming a
291: * 60 minute hour.
292: * <p>
293: * This method allows you to convert between different types of period.
294: * However to achieve this it makes the assumption that all hours are 60 minutes long.
295: * This may not be true for some unusual chronologies. However, it is included
296: * as it is a useful operation for many applications and business rules.
297: *
298: * @return a period representing the number of minutes for this number of hours
299: * @throws ArithmeticException if the number of minutes is too large to be represented
300: */
301: public Minutes toStandardMinutes() {
302: return Minutes.minutes(FieldUtils.safeMultiply(getValue(),
303: DateTimeConstants.MINUTES_PER_HOUR));
304: }
305:
306: /**
307: * Converts this period in hours to a period in seconds assuming a
308: * 60 minute hour and 60 second minute.
309: * <p>
310: * This method allows you to convert between different types of period.
311: * However to achieve this it makes the assumption that all hours are
312: * 60 minutes long and all minutes are 60 seconds long.
313: * This may not be true for some unusual chronologies. However, it is included
314: * as it is a useful operation for many applications and business rules.
315: *
316: * @return a period representing the number of seconds for this number of hours
317: * @throws ArithmeticException if the number of seconds is too large to be represented
318: */
319: public Seconds toStandardSeconds() {
320: return Seconds.seconds(FieldUtils.safeMultiply(getValue(),
321: DateTimeConstants.SECONDS_PER_HOUR));
322: }
323:
324: //-----------------------------------------------------------------------
325: /**
326: * Converts this period in hours to a duration in milliseconds assuming a
327: * 60 minute hour and 60 second minute.
328: * <p>
329: * This method allows you to convert from a period to a duration.
330: * However to achieve this it makes the assumption that all hours are
331: * 60 minutes and all minutes are 60 seconds. This might not be true for an
332: * unusual chronology, for example one that takes leap seconds into account.
333: * However, the method is included as it is a useful operation for many
334: * applications and business rules.
335: *
336: * @return a duration equivalent to this number of hours
337: */
338: public Duration toStandardDuration() {
339: long hours = getValue(); // assign to a long
340: return new Duration(hours * DateTimeConstants.MILLIS_PER_HOUR);
341: }
342:
343: //-----------------------------------------------------------------------
344: /**
345: * Gets the number of hours that this period represents.
346: *
347: * @return the number of hours in the period
348: */
349: public int getHours() {
350: return getValue();
351: }
352:
353: //-----------------------------------------------------------------------
354: /**
355: * Returns a new instance with the specified number of hours added.
356: * <p>
357: * This instance is immutable and unaffected by this method call.
358: *
359: * @param hours the amount of hours to add, may be negative
360: * @return the new period plus the specified number of hours
361: * @throws ArithmeticException if the result overflows an int
362: */
363: public Hours plus(int hours) {
364: if (hours == 0) {
365: return this ;
366: }
367: return Hours.hours(FieldUtils.safeAdd(getValue(), hours));
368: }
369:
370: /**
371: * Returns a new instance with the specified number of hours added.
372: * <p>
373: * This instance is immutable and unaffected by this method call.
374: *
375: * @param hours the amount of hours to add, may be negative, null means zero
376: * @return the new period plus the specified number of hours
377: * @throws ArithmeticException if the result overflows an int
378: */
379: public Hours plus(Hours hours) {
380: if (hours == null) {
381: return this ;
382: }
383: return plus(hours.getValue());
384: }
385:
386: //-----------------------------------------------------------------------
387: /**
388: * Returns a new instance with the specified number of hours taken away.
389: * <p>
390: * This instance is immutable and unaffected by this method call.
391: *
392: * @param hours the amount of hours to take away, may be negative
393: * @return the new period minus the specified number of hours
394: * @throws ArithmeticException if the result overflows an int
395: */
396: public Hours minus(int hours) {
397: return plus(FieldUtils.safeNegate(hours));
398: }
399:
400: /**
401: * Returns a new instance with the specified number of hours taken away.
402: * <p>
403: * This instance is immutable and unaffected by this method call.
404: *
405: * @param hours the amount of hours to take away, may be negative, null means zero
406: * @return the new period minus the specified number of hours
407: * @throws ArithmeticException if the result overflows an int
408: */
409: public Hours minus(Hours hours) {
410: if (hours == null) {
411: return this ;
412: }
413: return minus(hours.getValue());
414: }
415:
416: //-----------------------------------------------------------------------
417: /**
418: * Returns a new instance with the hours multiplied by the specified scalar.
419: * <p>
420: * This instance is immutable and unaffected by this method call.
421: *
422: * @param scalar the amount to multiply by, may be negative
423: * @return the new period multiplied by the specified scalar
424: * @throws ArithmeticException if the result overflows an int
425: */
426: public Hours multipliedBy(int scalar) {
427: return Hours.hours(FieldUtils.safeMultiply(getValue(), scalar));
428: }
429:
430: /**
431: * Returns a new instance with the hours divided by the specified divisor.
432: * The calculation uses integer division, thus 3 divided by 2 is 1.
433: * <p>
434: * This instance is immutable and unaffected by this method call.
435: *
436: * @param divisor the amount to divide by, may be negative
437: * @return the new period divided by the specified divisor
438: * @throws ArithmeticException if the divisor is zero
439: */
440: public Hours dividedBy(int divisor) {
441: if (divisor == 1) {
442: return this ;
443: }
444: return Hours.hours(getValue() / divisor);
445: }
446:
447: //-----------------------------------------------------------------------
448: /**
449: * Returns a new instance with the hours value negated.
450: *
451: * @return the new period with a negated value
452: * @throws ArithmeticException if the result overflows an int
453: */
454: public Hours negated() {
455: return Hours.hours(FieldUtils.safeNegate(getValue()));
456: }
457:
458: //-----------------------------------------------------------------------
459: /**
460: * Is this hours instance greater than the specified number of hours.
461: *
462: * @param other the other period, null means zero
463: * @return true if this hours instance is greater than the specified one
464: */
465: public boolean isGreaterThan(Hours other) {
466: if (other == null) {
467: return getValue() > 0;
468: }
469: return getValue() > other.getValue();
470: }
471:
472: /**
473: * Is this hours instance less than the specified number of hours.
474: *
475: * @param other the other period, null means zero
476: * @return true if this hours instance is less than the specified one
477: */
478: public boolean isLessThan(Hours other) {
479: if (other == null) {
480: return getValue() < 0;
481: }
482: return getValue() < other.getValue();
483: }
484:
485: //-----------------------------------------------------------------------
486: /**
487: * Gets this instance as a String in the ISO8601 duration format.
488: * <p>
489: * For example, "PT4H" represents 4 hours.
490: *
491: * @return the value as an ISO8601 string
492: */
493: public String toString() {
494: return "PT" + String.valueOf(getValue()) + "H";
495: }
496:
497: }
|