Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  Copyright 2001-2011 Stephen Colebourne
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
 package org.joda.time.base;
 
 
BasePeriod is an abstract implementation of ReadablePeriod that stores data in a PeriodType and an int[].

This class should generally not be used directly by API users. The org.joda.time.ReadablePeriod interface should be used when different kinds of period objects are to be referenced.

BasePeriod subclasses may be mutable and not thread-safe.

Author(s):
Brian S O'Neill
Stephen Colebourne
Since:
1.0
 
 public abstract class BasePeriod
         extends AbstractPeriod
         implements ReadablePeriodSerializable {

    
Serialization version
 
     private static final long serialVersionUID = -2110953284060001145L;
    
Serialization version
 
     private static final ReadablePeriod DUMMY_PERIOD = new AbstractPeriod() {
         public int getValue(int index) {
             return 0;
         }
         public PeriodType getPeriodType() {
             return PeriodType.time();
         }
     };

    
The type of period
 
     private final PeriodType iType;
    
The values
 
     private final int[] iValues;
 
     //-----------------------------------------------------------------------
     
Creates a period from a set of field values.

Parameters:
years amount of years in this period, which must be zero if unsupported
months amount of months in this period, which must be zero if unsupported
weeks amount of weeks in this period, which must be zero if unsupported
days amount of days in this period, which must be zero if unsupported
hours amount of hours in this period, which must be zero if unsupported
minutes amount of minutes in this period, which must be zero if unsupported
seconds amount of seconds in this period, which must be zero if unsupported
millis amount of milliseconds in this period, which must be zero if unsupported
type which set of fields this period supports
Throws:
java.lang.IllegalArgumentException if period type is invalid
java.lang.IllegalArgumentException if an unsupported field's value is non-zero
 
     protected BasePeriod(int yearsint monthsint weeksint days,
                          int hoursint minutesint secondsint millis,
                          PeriodType type) {
         super();
         type = checkPeriodType(type);
          = type;
          = setPeriodInternal(yearsmonthsweeksdayshoursminutessecondsmillis); // internal method
     }

    
Creates a period from the given interval endpoints.

Parameters:
startInstant interval start, in milliseconds
endInstant interval end, in milliseconds
type which set of fields this period supports, null means standard
chrono the chronology to use, null means ISO default
Throws:
java.lang.IllegalArgumentException if period type is invalid
    protected BasePeriod(long startInstantlong endInstantPeriodType typeChronology chrono) {
        super();
        type = checkPeriodType(type);
        chrono = DateTimeUtils.getChronology(chrono);
         = type;
         = chrono.get(thisstartInstantendInstant);
    }

    
Creates a period from the given interval endpoints.

Parameters:
startInstant interval start, null means now
endInstant interval end, null means now
type which set of fields this period supports, null means standard
Throws:
java.lang.IllegalArgumentException if period type is invalid
    protected BasePeriod(ReadableInstant startInstantReadableInstant endInstantPeriodType type) {
        super();
        type = checkPeriodType(type);
        if (startInstant == null && endInstant == null) {
             = type;
             = new int[size()];
        } else {
            long startMillis = DateTimeUtils.getInstantMillis(startInstant);
            long endMillis = DateTimeUtils.getInstantMillis(endInstant);
            Chronology chrono = DateTimeUtils.getIntervalChronology(startInstantendInstant);
             = type;
             = chrono.get(thisstartMillisendMillis);
        }
    }

    
Creates a period from the given duration and end point.

The two partials must contain the same fields, thus you can specify two LocalDate objects, or two LocalTime objects, but not one of each. As these are Partial objects, time zones have no effect on the result.

The two partials must also both be contiguous - see org.joda.time.DateTimeUtils.isContiguous(org.joda.time.ReadablePartial) for a definition. Both LocalDate and LocalTime are contiguous.

Parameters:
start the start of the period, must not be null
end the end of the period, must not be null
type which set of fields this period supports, null means standard
Throws:
java.lang.IllegalArgumentException if the partials are null or invalid
Since:
1.1
    protected BasePeriod(ReadablePartial startReadablePartial endPeriodType type) {
        super();
        if (start == null || end == null) {
            throw new IllegalArgumentException("ReadablePartial objects must not be null");
        }
        if (start instanceof BaseLocal && end instanceof BaseLocal && start.getClass() == end.getClass()) {
            // for performance
            type = checkPeriodType(type);
            long startMillis = ((BaseLocalstart).getLocalMillis();
            long endMillis = ((BaseLocalend).getLocalMillis();
            Chronology chrono = start.getChronology();
            chrono = DateTimeUtils.getChronology(chrono);
             = type;
             = chrono.get(thisstartMillisendMillis);
        } else {
            if (start.size() != end.size()) {
                throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields");
            }
            for (int i = 0, isize = start.size(); i < isizei++) {
                if (start.getFieldType(i) != end.getFieldType(i)) {
                    throw new IllegalArgumentException("ReadablePartial objects must have the same set of fields");
                }
            }
            if (DateTimeUtils.isContiguous(start) == false) {
                throw new IllegalArgumentException("ReadablePartial objects must be contiguous");
            }
             = checkPeriodType(type);
            Chronology chrono = DateTimeUtils.getChronology(start.getChronology()).withUTC();
             = chrono.get(thischrono.set(start, 0L), chrono.set(end, 0L));
        }
    }

    
Creates a period from the given start point and duration.

Parameters:
startInstant the interval start, null means now
duration the duration of the interval, null means zero-length
type which set of fields this period supports, null means standard
    protected BasePeriod(ReadableInstant startInstantReadableDuration durationPeriodType type) {
        super();
        type = checkPeriodType(type);
        long startMillis = DateTimeUtils.getInstantMillis(startInstant);
        long durationMillis = DateTimeUtils.getDurationMillis(duration);
        long endMillis = FieldUtils.safeAdd(startMillisdurationMillis);
        Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
         = type;
         = chrono.get(thisstartMillisendMillis);
    }

    
Creates a period from the given duration and end point.

Parameters:
duration the duration of the interval, null means zero-length
endInstant the interval end, null means now
type which set of fields this period supports, null means standard
    protected BasePeriod(ReadableDuration durationReadableInstant endInstantPeriodType type) {
        super();
        type = checkPeriodType(type);
        long durationMillis = DateTimeUtils.getDurationMillis(duration);
        long endMillis = DateTimeUtils.getInstantMillis(endInstant);
        long startMillis = FieldUtils.safeSubtract(endMillisdurationMillis);
        Chronology chrono = DateTimeUtils.getInstantChronology(endInstant);
         = type;
         = chrono.get(thisstartMillisendMillis);
    }

    
Creates a period from the given millisecond duration with the standard period type and ISO rules, ensuring that the calculation is performed with the time-only period type.

The calculation uses the hour, minute, second and millisecond fields.

Parameters:
duration the duration, in milliseconds
    protected BasePeriod(long duration) {
        super();
        // bug [3264409]
        // calculation uses period type from a period object (bad design)
        // thus we use a dummy period object with the time type
         = PeriodType.standard();
        int[] values = ISOChronology.getInstanceUTC().get(duration);
         = new int[8];
        System.arraycopy(values, 0, , 4, 4);
    }

    
Creates a period from the given millisecond duration, which is only really suitable for durations less than one day.

Only fields that are precise will be used. Thus the largest precise field may have a large value.

Parameters:
duration the duration, in milliseconds
type which set of fields this period supports, null means standard
chrono the chronology to use, null means ISO default
Throws:
java.lang.IllegalArgumentException if period type is invalid
    protected BasePeriod(long durationPeriodType typeChronology chrono) {
        super();
        type = checkPeriodType(type);
        chrono = DateTimeUtils.getChronology(chrono);
         = type;
         = chrono.get(thisduration);
    }

    
Creates a new period based on another using the org.joda.time.convert.ConverterManager.

Parameters:
period the period to convert
type which set of fields this period supports, null means use type from object
chrono the chronology to use, null means ISO default
Throws:
java.lang.IllegalArgumentException if period is invalid
java.lang.IllegalArgumentException if an unsupported field's value is non-zero
    protected BasePeriod(Object periodPeriodType typeChronology chrono) {
        super();
        PeriodConverter converter = ConverterManager.getInstance().getPeriodConverter(period);
        type = (type == null ? converter.getPeriodType(period) : type);
        type = checkPeriodType(type);
         = type;
        if (this instanceof ReadWritablePeriod) {
             = new int[size()];
            chrono = DateTimeUtils.getChronology(chrono);
            converter.setInto((ReadWritablePeriodthisperiodchrono);
        } else {
             = new MutablePeriod(periodtypechrono).getValues();
        }
    }

    
Constructor used when we trust ourselves. Do not expose publically.

Parameters:
values the values to use, not null, not cloned
type which set of fields this period supports, not null
    protected BasePeriod(int[] valuesPeriodType type) {
        super();
         = type;
         = values;
    }
    //-----------------------------------------------------------------------
    
Validates a period type, converting nulls to a default value and checking the type is suitable for this instance.

Parameters:
type the type to check, may be null
Returns:
the validated type to use, not null
Throws:
java.lang.IllegalArgumentException if the period type is invalid
    protected PeriodType checkPeriodType(PeriodType type) {
        return DateTimeUtils.getPeriodType(type);
    }
    //-----------------------------------------------------------------------
    
Gets the period type.

Returns:
the period type
    public PeriodType getPeriodType() {
        return ;
    }

    
Gets the value at the specified index.

Parameters:
index the index to retrieve
Returns:
the value of the field at the specified index
Throws:
java.lang.IndexOutOfBoundsException if the index is invalid
    public int getValue(int index) {
        return [index];
    }
    //-----------------------------------------------------------------------
    
Gets the total millisecond duration of this period relative to a start instant.

This method adds the period to the specified instant in order to calculate the duration.

An instant must be supplied as the duration of a period varies. For example, a period of 1 month could vary between the equivalent of 28 and 31 days in milliseconds due to different length months. Similarly, a day can vary at Daylight Savings cutover, typically between 23 and 25 hours.

Parameters:
startInstant the instant to add the period to, thus obtaining the duration
Returns:
the total length of the period as a duration relative to the start instant
Throws:
java.lang.ArithmeticException if the millis exceeds the capacity of the duration
    public Duration toDurationFrom(ReadableInstant startInstant) {
        long startMillis = DateTimeUtils.getInstantMillis(startInstant);
        Chronology chrono = DateTimeUtils.getInstantChronology(startInstant);
        long endMillis = chrono.add(thisstartMillis, 1);
        return new Duration(startMillisendMillis);
    }

    
Gets the total millisecond duration of this period relative to an end instant.

This method subtracts the period from the specified instant in order to calculate the duration.

An instant must be supplied as the duration of a period varies. For example, a period of 1 month could vary between the equivalent of 28 and 31 days in milliseconds due to different length months. Similarly, a day can vary at Daylight Savings cutover, typically between 23 and 25 hours.

Parameters:
endInstant the instant to subtract the period from, thus obtaining the duration
Returns:
the total length of the period as a duration relative to the end instant
Throws:
java.lang.ArithmeticException if the millis exceeds the capacity of the duration
    public Duration toDurationTo(ReadableInstant endInstant) {
        long endMillis = DateTimeUtils.getInstantMillis(endInstant);
        Chronology chrono = DateTimeUtils.getInstantChronology(endInstant);
        long startMillis = chrono.add(thisendMillis, -1);
        return new Duration(startMillisendMillis);
    }
    //-----------------------------------------------------------------------
    
Checks whether a field type is supported, and if so adds the new value to the relevant index in the specified array.

Parameters:
type the field type
values the array to update
newValue the new value to store if successful
    private void checkAndUpdate(DurationFieldType typeint[] valuesint newValue) {
        int index = indexOf(type);
        if (index == -1) {
            if (newValue != 0) {
                throw new IllegalArgumentException(
                    "Period does not support field '" + type.getName() + "'");
            }
        } else {
            values[index] = newValue;
        }
    }
    //-----------------------------------------------------------------------
    
Sets all the fields of this period from another.

Parameters:
period the period to copy from, not null
Throws:
java.lang.IllegalArgumentException if an unsupported field's value is non-zero
    protected void setPeriod(ReadablePeriod period) {
        if (period == null) {
            setValues(new int[size()]);
        } else {
            setPeriodInternal(period);
        }
    }

    
Private method called from constructor.
    private void setPeriodInternal(ReadablePeriod period) {
        int[] newValues = new int[size()];
        for (int i = 0, isize = period.size(); i < isizei++) {
            DurationFieldType type = period.getFieldType(i);
            int value = period.getValue(i);
            checkAndUpdate(typenewValuesvalue);
        }
        setValues(newValues);
    }

    
Sets the eight standard the fields in one go.

Parameters:
years amount of years in this period, which must be zero if unsupported
months amount of months in this period, which must be zero if unsupported
weeks amount of weeks in this period, which must be zero if unsupported
days amount of days in this period, which must be zero if unsupported
hours amount of hours in this period, which must be zero if unsupported
minutes amount of minutes in this period, which must be zero if unsupported
seconds amount of seconds in this period, which must be zero if unsupported
millis amount of milliseconds in this period, which must be zero if unsupported
Throws:
java.lang.IllegalArgumentException if an unsupported field's value is non-zero
    protected void setPeriod(int yearsint monthsint weeksint days,
                             int hoursint minutesint secondsint millis) {
        int[] newValues = setPeriodInternal(yearsmonthsweeksdayshoursminutessecondsmillis);
        setValues(newValues);
    }

    
Private method called from constructor.
    private int[] setPeriodInternal(int yearsint monthsint weeksint days,
                                   int hoursint minutesint secondsint millis) {
        int[] newValues = new int[size()];
        checkAndUpdate(DurationFieldType.years(), newValuesyears);
        checkAndUpdate(DurationFieldType.months(), newValuesmonths);
        checkAndUpdate(DurationFieldType.weeks(), newValuesweeks);
        checkAndUpdate(DurationFieldType.days(), newValuesdays);
        checkAndUpdate(DurationFieldType.hours(), newValueshours);
        checkAndUpdate(DurationFieldType.minutes(), newValuesminutes);
        checkAndUpdate(DurationFieldType.seconds(), newValuesseconds);
        checkAndUpdate(DurationFieldType.millis(), newValuesmillis);
        return newValues;
    }
    //-----------------------------------------------------------------------
    
Sets the value of a field in this period.

Parameters:
field the field to set
value the value to set
Throws:
java.lang.IllegalArgumentException if field is is null or not supported.
    protected void setField(DurationFieldType fieldint value) {
        setFieldInto(fieldvalue);
    }

    
Sets the value of a field in this period.

Parameters:
values the array of values to update
field the field to set
value the value to set
Throws:
java.lang.IllegalArgumentException if field is null or not supported.
    protected void setFieldInto(int[] valuesDurationFieldType fieldint value) {
        int index = indexOf(field);
        if (index == -1) {
            if (value != 0 || field == null) {
                throw new IllegalArgumentException(
                    "Period does not support field '" + field + "'");
            }
        } else {
            values[index] = value;
        }
    }

    
Adds the value of a field in this period.

Parameters:
field the field to set
value the value to set
Throws:
java.lang.IllegalArgumentException if field is is null or not supported.
    protected void addField(DurationFieldType fieldint value) {
        addFieldInto(fieldvalue);
    }

    
Adds the value of a field in this period.

Parameters:
values the array of values to update
field the field to set
value the value to set
Throws:
java.lang.IllegalArgumentException if field is is null or not supported.
    protected void addFieldInto(int[] valuesDurationFieldType fieldint value) {
        int index = indexOf(field);
        if (index == -1) {
            if (value != 0 || field == null) {
                throw new IllegalArgumentException(
                    "Period does not support field '" + field + "'");
            }
        } else {
            values[index] = FieldUtils.safeAdd(values[index], value);
        }
    }

    
Merges the fields from another period.

Parameters:
period the period to add from, not null
Throws:
java.lang.IllegalArgumentException if an unsupported field's value is non-zero
    protected void mergePeriod(ReadablePeriod period) {
        if (period != null) {
            setValues(mergePeriodInto(getValues(), period));
        }
    }

    
Merges the fields from another period.

Parameters:
values the array of values to update
period the period to add from, not null
Returns:
the updated values
Throws:
java.lang.IllegalArgumentException if an unsupported field's value is non-zero
    protected int[] mergePeriodInto(int[] valuesReadablePeriod period) {
        for (int i = 0, isize = period.size(); i < isizei++) {
            DurationFieldType type = period.getFieldType(i);
            int value = period.getValue(i);
            checkAndUpdate(typevaluesvalue);
        }
        return values;
    }

    
Adds the fields from another period.

Parameters:
period the period to add from, not null
Throws:
java.lang.IllegalArgumentException if an unsupported field's value is non-zero
    protected void addPeriod(ReadablePeriod period) {
        if (period != null) {
            setValues(addPeriodInto(getValues(), period));
        }
    }

    
Adds the fields from another period.

Parameters:
values the array of values to update
period the period to add from, not null
Returns:
the updated values
Throws:
java.lang.IllegalArgumentException if an unsupported field's value is non-zero
    protected int[] addPeriodInto(int[] valuesReadablePeriod period) {
        for (int i = 0, isize = period.size(); i < isizei++) {
            DurationFieldType type = period.getFieldType(i);
            int value = period.getValue(i);
            if (value != 0) {
                int index = indexOf(type);
                if (index == -1) {
                    throw new IllegalArgumentException(
                        "Period does not support field '" + type.getName() + "'");
                } else {
                    values[index] = FieldUtils.safeAdd(getValue(index), value);
                }
            }
        }
        return values;
    }
    //-----------------------------------------------------------------------
    
Sets the value of the field at the specified index.

Parameters:
index the index
value the value to set
Throws:
java.lang.IndexOutOfBoundsException if the index is invalid
    protected void setValue(int indexint value) {
        [index] = value;
    }

    
Sets the values of all fields.

In version 2.0 and later, this method copies the array into the original. This is because the instance variable has been changed to be final to satisfy the Java Memory Model. This only impacts subclasses that are mutable.

Parameters:
values the array of values
    protected void setValues(int[] values) {
        System.arraycopy(values, 0, , 0, .);
    }
New to GrepCode? Check out our FAQ X