Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  Copyright 2001-2013 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.chrono;
 
 
Wraps another Chronology to add support for time zones.

ZonedChronology is thread-safe and immutable.

Author(s):
Brian S O'Neill
Stephen Colebourne
Since:
1.0
 
 public final class ZonedChronology extends AssembledChronology {

    
Serialization lock
 
     private static final long serialVersionUID = -1079258847191166848L;

    
Create a ZonedChronology for any chronology, overriding any time zone it may already have.

Parameters:
base base chronology to wrap
zone the time zone
Throws:
java.lang.IllegalArgumentException if chronology or time zone is null
 
     public static ZonedChronology getInstance(Chronology baseDateTimeZone zone) {
         if (base == null) {
             throw new IllegalArgumentException("Must supply a chronology");
         }
         base = base.withUTC();
         if (base == null) {
             throw new IllegalArgumentException("UTC chronology must not be null");
         }
         if (zone == null) {
             throw new IllegalArgumentException("DateTimeZone must not be null");
         }
         return new ZonedChronology(basezone);
     }
 
     static boolean useTimeArithmetic(DurationField field) {
         // Use time of day arithmetic rules for unit durations less than
         // typical time zone offsets.
         return field != null && field.getUnitMillis() < . * 12;
     }

    
Restricted constructor

Parameters:
base base chronology to wrap
zone the time zone
 
     private ZonedChronology(Chronology baseDateTimeZone zone) {
         super(basezone);
     }
 
     public DateTimeZone getZone() {
         return (DateTimeZone)getParam();
     }
 
     public Chronology withUTC() {
         return getBase();
     }
 
     public Chronology withZone(DateTimeZone zone) {
         if (zone == null) {
             zone = DateTimeZone.getDefault();
         }
         if (zone == getParam()) {
             return this;
         }
         if (zone == .) {
            return getBase();
        }
        return new ZonedChronology(getBase(), zone);
    }
    public long getDateTimeMillis(int yearint monthOfYearint dayOfMonth,
                                  int millisOfDay)
        throws IllegalArgumentException
    {
        return localToUTC(getBase().getDateTimeMillis
                          (yearmonthOfYeardayOfMonthmillisOfDay));
    }
    public long getDateTimeMillis(int yearint monthOfYearint dayOfMonth,
                                  int hourOfDayint minuteOfHour,
                                  int secondOfMinuteint millisOfSecond)
        throws IllegalArgumentException
    {
        return localToUTC(getBase().getDateTimeMillis
                          (yearmonthOfYeardayOfMonth
                           hourOfDayminuteOfHoursecondOfMinutemillisOfSecond));
    }
    public long getDateTimeMillis(long instant,
                                  int hourOfDayint minuteOfHour,
                                  int secondOfMinuteint millisOfSecond)
        throws IllegalArgumentException
    {
        return localToUTC(getBase().getDateTimeMillis
                          (instant + getZone().getOffset(instant),
                           hourOfDayminuteOfHoursecondOfMinutemillisOfSecond));
    }

    

Parameters:
localInstant the instant from 1970-01-01T00:00:00 local time
Returns:
the instant from 1970-01-01T00:00:00Z
    private long localToUTC(long localInstant) {
        DateTimeZone zone = getZone();
        int offset = zone.getOffsetFromLocal(localInstant);
        localInstant -= offset;
        if (offset != zone.getOffset(localInstant)) {
            throw new IllegalInstantException(localInstantzone.getID());
        }
        return localInstant;
    }
    protected void assemble(Fields fields) {
        // Keep a local cache of converted fields so as not to create redundant
        // objects.
        HashMap<ObjectObjectconverted = new HashMap<ObjectObject>();
        // Convert duration fields...
        fields.eras = convertField(fields.erasconverted);
        fields.centuries = convertField(fields.centuriesconverted);
        fields.years = convertField(fields.yearsconverted);
        fields.months = convertField(fields.monthsconverted);
        fields.weekyears = convertField(fields.weekyearsconverted);
        fields.weeks = convertField(fields.weeksconverted);
        fields.days = convertField(fields.daysconverted);
        fields.halfdays = convertField(fields.halfdaysconverted);
        fields.hours = convertField(fields.hoursconverted);
        fields.minutes = convertField(fields.minutesconverted);
        fields.seconds = convertField(fields.secondsconverted);
        fields.millis = convertField(fields.millisconverted);
        // Convert datetime fields...
        fields.year = convertField(fields.yearconverted);
        fields.yearOfEra = convertField(fields.yearOfEraconverted);
        fields.yearOfCentury = convertField(fields.yearOfCenturyconverted);
        fields.centuryOfEra = convertField(fields.centuryOfEraconverted);
        fields.era = convertField(fields.eraconverted);
        fields.dayOfWeek = convertField(fields.dayOfWeekconverted);
        fields.dayOfMonth = convertField(fields.dayOfMonthconverted);
        fields.dayOfYear = convertField(fields.dayOfYearconverted);
        fields.monthOfYear = convertField(fields.monthOfYearconverted);
        fields.weekOfWeekyear = convertField(fields.weekOfWeekyearconverted);
        fields.weekyear = convertField(fields.weekyearconverted);
        fields.weekyearOfCentury = convertField(fields.weekyearOfCenturyconverted);
        fields.millisOfSecond = convertField(fields.millisOfSecondconverted);
        fields.millisOfDay = convertField(fields.millisOfDayconverted);
        fields.secondOfMinute = convertField(fields.secondOfMinuteconverted);
        fields.secondOfDay = convertField(fields.secondOfDayconverted);
        fields.minuteOfHour = convertField(fields.minuteOfHourconverted);
        fields.minuteOfDay = convertField(fields.minuteOfDayconverted);
        fields.hourOfDay = convertField(fields.hourOfDayconverted);
        fields.hourOfHalfday = convertField(fields.hourOfHalfdayconverted);
        fields.clockhourOfDay = convertField(fields.clockhourOfDayconverted);
        fields.clockhourOfHalfday = convertField(fields.clockhourOfHalfdayconverted);
        fields.halfdayOfDay = convertField(fields.halfdayOfDayconverted);
    }
    private DurationField convertField(DurationField fieldHashMap<ObjectObjectconverted) {
        if (field == null || !field.isSupported()) {
            return field;
        }
        if (converted.containsKey(field)) {
            return (DurationField)converted.get(field);
        }
        ZonedDurationField zonedField = new ZonedDurationField(fieldgetZone());
        converted.put(fieldzonedField);
        return zonedField;
    }
    private DateTimeField convertField(DateTimeField fieldHashMap<ObjectObjectconverted) {
        if (field == null || !field.isSupported()) {
            return field;
        }
        if (converted.containsKey(field)) {
            return (DateTimeField)converted.get(field);
        }
        ZonedDateTimeField zonedField =
            new ZonedDateTimeField(fieldgetZone(),
                                   convertField(field.getDurationField(), converted),
                                   convertField(field.getRangeDurationField(), converted),
                                   convertField(field.getLeapDurationField(), converted));
        converted.put(fieldzonedField);
        return zonedField;
    }
    //-----------------------------------------------------------------------
    
A zoned chronology is only equal to a zoned chronology with the same base chronology and zone.

Parameters:
obj the object to compare to
Returns:
true if equal
Since:
1.4
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof ZonedChronology == false) {
            return false;
        }
        ZonedChronology chrono = (ZonedChronologyobj;
        return
            getBase().equals(chrono.getBase()) &&
            getZone().equals(chrono.getZone());
    }

    
A suitable hashcode for the chronology.

Returns:
the hashcode
Since:
1.4
    public int hashCode() {
        return 326565 + getZone().hashCode() * 11 + getBase().hashCode() * 7;
    }

    
A debugging string for the chronology.

Returns:
the debugging string
    public String toString() {
        return "ZonedChronology[" + getBase() + ", " + getZone().getID() + ']';
    }
    //-----------------------------------------------------------------------
    /*
     * Because time durations are typically smaller than time zone offsets, the
     * arithmetic methods subtract the original offset. This produces a more
     * expected behavior when crossing time zone offset transitions. For dates,
     * the new offset is subtracted off. This behavior, if applied to time
     * fields, can nullify or reverse an add when crossing a transition.
     */
    static class ZonedDurationField extends BaseDurationField {
        private static final long serialVersionUID = -485345310999208286L;
        final DurationField iField;
        final boolean iTimeField;
        final DateTimeZone iZone;
        ZonedDurationField(DurationField fieldDateTimeZone zone) {
            super(field.getType());
            if (!field.isSupported()) {
                throw new IllegalArgumentException();
            }
             = field;
             = useTimeArithmetic(field);
             = zone;
        }
        public boolean isPrecise() {
            return  ? .isPrecise() : .isPrecise() && this..isFixed();
        }
        public long getUnitMillis() {
            return .getUnitMillis();
        }
        public int getValue(long durationlong instant) {
            return .getValue(durationaddOffset(instant));
        }
        public long getValueAsLong(long durationlong instant) {
            return .getValueAsLong(durationaddOffset(instant));
        }
        public long getMillis(int valuelong instant) {
            return .getMillis(valueaddOffset(instant));
        }
        public long getMillis(long valuelong instant) {
            return .getMillis(valueaddOffset(instant));
        }
        public long add(long instantint value) {
            int offset = getOffsetToAdd(instant);
            instant = .add(instant + offsetvalue);
            return instant - ( ? offset : getOffsetFromLocalToSubtract(instant));
        }
        public long add(long instantlong value) {
            int offset = getOffsetToAdd(instant);
            instant = .add(instant + offsetvalue);
            return instant - ( ? offset : getOffsetFromLocalToSubtract(instant));
        }
        public int getDifference(long minuendInstantlong subtrahendInstant) {
            int offset = getOffsetToAdd(subtrahendInstant);
            return .getDifference
                (minuendInstant + ( ? offset : getOffsetToAdd(minuendInstant)),
                 subtrahendInstant + offset);
        }
        public long getDifferenceAsLong(long minuendInstantlong subtrahendInstant) {
            int offset = getOffsetToAdd(subtrahendInstant);
            return .getDifferenceAsLong
                (minuendInstant + ( ? offset : getOffsetToAdd(minuendInstant)),
                 subtrahendInstant + offset);
        }
        private int getOffsetToAdd(long instant) {
            int offset = this..getOffset(instant);
            long sum = instant + offset;
            // If there is a sign change, but the two values have the same sign...
            if ((instant ^ sum) < 0 && (instant ^ offset) >= 0) {
                throw new ArithmeticException("Adding time zone offset caused overflow");
            }
            return offset;
        }
        private int getOffsetFromLocalToSubtract(long instant) {
            int offset = this..getOffsetFromLocal(instant);
            long diff = instant - offset;
            // If there is a sign change, but the two values have different signs...
            if ((instant ^ diff) < 0 && (instant ^ offset) < 0) {
                throw new ArithmeticException("Subtracting time zone offset caused overflow");
            }
            return offset;
        }
        private long addOffset(long instant) {
            return .convertUTCToLocal(instant);
        }
    }

    
A DateTimeField that decorates another to add timezone behaviour.

This class converts passed in instants to local wall time, and vice versa on output.

    static final class ZonedDateTimeField extends BaseDateTimeField {
        @SuppressWarnings("unused")
        private static final long serialVersionUID = -3968986277775529794L;
        final DateTimeField iField;
        final DateTimeZone iZone;
        final DurationField iDurationField;
        final boolean iTimeField;
        final DurationField iRangeDurationField;
        final DurationField iLeapDurationField;
        ZonedDateTimeField(DateTimeField field,
                           DateTimeZone zone,
                           DurationField durationField,
                           DurationField rangeDurationField,
                           DurationField leapDurationField) {
            super(field.getType());
            if (!field.isSupported()) {
                throw new IllegalArgumentException();
            }
             = field;
             = zone;
             = durationField;
             = useTimeArithmetic(durationField);
             = rangeDurationField;
             = leapDurationField;
        }
        public boolean isLenient() {
            return .isLenient();
        }
        public int get(long instant) {
            long localInstant = .convertUTCToLocal(instant);
            return .get(localInstant);
        }
        public String getAsText(long instantLocale locale) {
            long localInstant = .convertUTCToLocal(instant);
            return .getAsText(localInstantlocale);
        }
        public String getAsShortText(long instantLocale locale) {
            long localInstant = .convertUTCToLocal(instant);
            return .getAsShortText(localInstantlocale);
        }
        public String getAsText(int fieldValueLocale locale) {
            return .getAsText(fieldValuelocale);
        }
        public String getAsShortText(int fieldValueLocale locale) {
            return .getAsShortText(fieldValuelocale);
        }
        public long add(long instantint value) {
            if () {
                int offset = getOffsetToAdd(instant);
                long localInstant = .add(instant + offsetvalue);
                return localInstant - offset;
            } else {
               long localInstant = .convertUTCToLocal(instant);
               localInstant = .add(localInstantvalue);
               return .convertLocalToUTC(localInstantfalseinstant);
            }
        }
        public long add(long instantlong value) {
            if () {
                int offset = getOffsetToAdd(instant);
                long localInstant = .add(instant + offsetvalue);
                return localInstant - offset;
            } else {
               long localInstant = .convertUTCToLocal(instant);
               localInstant = .add(localInstantvalue);
               return .convertLocalToUTC(localInstantfalseinstant);
            }
        }
        public long addWrapField(long instantint value) {
            if () {
                int offset = getOffsetToAdd(instant);
                long localInstant = .addWrapField(instant + offsetvalue);
                return localInstant - offset;
            } else {
                long localInstant = .convertUTCToLocal(instant);
                localInstant = .addWrapField(localInstantvalue);
                return .convertLocalToUTC(localInstantfalseinstant);
            }
        }
        public long set(long instantint value) {
            long localInstant = .convertUTCToLocal(instant);
            localInstant = .set(localInstantvalue);
            long result = .convertLocalToUTC(localInstantfalseinstant);
            if (get(result) != value) {
                IllegalInstantException cause = new IllegalInstantException(localInstant,  .getID());
                IllegalFieldValueException ex = new IllegalFieldValueException(.getType(), Integer.valueOf(value), cause.getMessage());
                ex.initCause(cause);
                throw ex;
            }
            return result;
        }
        public long set(long instantString textLocale locale) {
            // cannot verify that new value stuck because set may be lenient
            long localInstant = .convertUTCToLocal(instant);
            localInstant = .set(localInstanttextlocale);
            return .convertLocalToUTC(localInstantfalseinstant);
        }
        public int getDifference(long minuendInstantlong subtrahendInstant) {
            int offset = getOffsetToAdd(subtrahendInstant);
            return .getDifference
                (minuendInstant + ( ? offset : getOffsetToAdd(minuendInstant)),
                 subtrahendInstant + offset);
        }
        public long getDifferenceAsLong(long minuendInstantlong subtrahendInstant) {
            int offset = getOffsetToAdd(subtrahendInstant);
            return .getDifferenceAsLong
                (minuendInstant + ( ? offset : getOffsetToAdd(minuendInstant)),
                 subtrahendInstant + offset);
        }
        public final DurationField getDurationField() {
            return ;
        }
        public final DurationField getRangeDurationField() {
            return ;
        }
        public boolean isLeap(long instant) {
            long localInstant = .convertUTCToLocal(instant);
            return .isLeap(localInstant);
        }
        public int getLeapAmount(long instant) {
            long localInstant = .convertUTCToLocal(instant);
            return .getLeapAmount(localInstant);
        }
        public final DurationField getLeapDurationField() {
            return ;
        }
        public long roundFloor(long instant) {
            if () {
                int offset = getOffsetToAdd(instant);
                instant = .roundFloor(instant + offset);
                return instant - offset;
            } else {
                long localInstant = .convertUTCToLocal(instant);
                localInstant = .roundFloor(localInstant);
                return .convertLocalToUTC(localInstantfalseinstant);
            }
        }
        public long roundCeiling(long instant) {
            if () {
                int offset = getOffsetToAdd(instant);
                instant = .roundCeiling(instant + offset);
                return instant - offset;
            } else {
                long localInstant = .convertUTCToLocal(instant);
                localInstant = .roundCeiling(localInstant);
                return .convertLocalToUTC(localInstantfalseinstant);
            }
        }
        public long remainder(long instant) {
            long localInstant = .convertUTCToLocal(instant);
            return .remainder(localInstant);
        }
        public int getMinimumValue() {
            return .getMinimumValue();
        }
        public int getMinimumValue(long instant) {
            long localInstant = .convertUTCToLocal(instant);
            return .getMinimumValue(localInstant);
        }
        public int getMinimumValue(ReadablePartial instant) {
            return .getMinimumValue(instant);
        }
        public int getMinimumValue(ReadablePartial instantint[] values) {
            return .getMinimumValue(instantvalues);
        }
        public int getMaximumValue() {
            return .getMaximumValue();
        }
        public int getMaximumValue(long instant) {
            long localInstant = .convertUTCToLocal(instant);
            return .getMaximumValue(localInstant);
        }
        public int getMaximumValue(ReadablePartial instant) {
            return .getMaximumValue(instant);
        }
        public int getMaximumValue(ReadablePartial instantint[] values) {
            return .getMaximumValue(instantvalues);
        }
        public int getMaximumTextLength(Locale locale) {
            return .getMaximumTextLength(locale);
        }
        public int getMaximumShortTextLength(Locale locale) {
            return .getMaximumShortTextLength(locale);
        }
        private int getOffsetToAdd(long instant) {
            int offset = this..getOffset(instant);
            long sum = instant + offset;
            // If there is a sign change, but the two values have the same sign...
            if ((instant ^ sum) < 0 && (instant ^ offset) >= 0) {
                throw new ArithmeticException("Adding time zone offset caused overflow");
            }
            return offset;
        }
    }
New to GrepCode? Check out our FAQ X